python - 如何在 Python 中动态分配内存

标签 python memory heap-memory

python 中是否有任何方法,我可以使用它从堆中获取一 block 内存,并使用一个变量来引用它。就像关键字“new”,或者其他语言中的函数malloc():

Object *obj = (Object *) malloc(sizeof(Object)); 
Object *obj = new Object();

在项目中,我的程序在不确定的时间间隔内等待接收一些正确的字节长度的数据。

我以前是这样的:

void receive()// callback
{
  if(getSize()<=sizeof(DataStruct))
  {
   DataStruct *pData=malloc(sizeof(DataStruct));
   if(recvData(pData)>0)
   list_add(globalList,pData);
  }   
}

void worker()
{
  init()
  while(!isFinish)
 {
  dataProcess(globalList);
 }

}

现在,我想将这些旧项目迁移到 python,我尝试这样做:

def reveive():
 data=dataRecv()
 globalList.append(data)

但是,我得到列表中的所有项目都是相同的,并且等于最新收到的项目。很明显,所有列表项都指向相同的内存地址,我想在每次调用函数时获得一个新的内存地址。

最佳答案

在 python 中相当于“new”的是只使用一个构造函数,例如:

new_list = list() # or [] - expandable heterogeneous list
new_dict = dict() # expandable hash table
new_obj = CustomObject() # assuming CustomObject has been defined

由于您是从 C 移植的,因此需要注意一些事项。 python中的一切都是对象包括整数,大部分变量只是引用,但是整数和字符串等标量变量的规则与容器不同,例如:

a = 2   # a is a reference to 2
b = a   # b is a reference to 'a'
b = 3   # b now points to 3, while 'a' continues to point to 2

但是:

alist = ['eggs', 2, 'juice']  # alist is reference to a new list
blist = alist # blist is a reference; changing blist affects alist
blist.append('coffee') # alist and blist both point to 
                       # ['eggs', 2, 'juice', 'coffee']

如果您愿意,您可以预先分配大小,但在 Python 中通常不会给您带来太多好处。以下是有效的:

new_list4k = [None]*4096 # initialize to list of 4096 None's 
new_list4k = [0]*4096    # initialize to 4096 0's
big_list = []
big_list.extend(new_list4k) # resizes big_list to accomodate at least 4k items

如果您想确保不会发生内存泄漏,请尽可能多地使用局部变量,例如,在一个函数内,这样您就不必担心事情超出范围。

为了高效的矢量化操作(以及更低的内存占用),请使用 numpy 数组。

import numpy as np
my_array = np.zeros(8192) # create a fixed array length of 8K elements
my_array += 4             # fills everything with 4

我加了两分钱: 我可能首先会问您的主要目标是什么。有 pythonic 的做事方式,同时尝试优化程序执行速度或最小内存占用。然后是尝试在尽可能短的时间内移植程序。有时它们都相交,但更常见的是,您会发现 pythonic 方式可以快速翻译但内存要求更高。从 python 获得更高的性能可能需要专注的经验。 祝你好运!

关于python - 如何在 Python 中动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009008/

相关文章:

python - 所有对象都是按值返回而不是按引用返回吗?

c - 何时释放 mex 文件中分配的内存

python - 为什么 Python 列表的内存使用量小于预期?

hadoop - 在RecordReader初始化之前,Hadoop EMR作业的内存不足

c++ - 检索堆内存大小及其使用统计信息等...?

python - 在 Mac Yosemite 上安装和使用 pygame

python - PyQt5 固定窗口大小

python - 使用与字符串同名的变量执行操作

c - 为什么多次调用 calloc 会使我的应用程序崩溃?

java - Java内存泄漏是否总是出现在旧代消耗中?