如何在Python中动态分配内存

lb *_* lb 5 python memory heap

python中有什么方法可以用来从堆中获取内存块,并可以使用变量来引用它。就像关键字“ new”或malloc()其他语言的函数一样:

Object *obj = (Object *) malloc(sizeof(Object)); 
Object *obj = new Object();
Run Code Online (Sandbox Code Playgroud)

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

我习惯这样:

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);
 }

}
Run Code Online (Sandbox Code Playgroud)

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

def reveive():
 data=dataRecv()
 globalList.append(data)
Run Code Online (Sandbox Code Playgroud)

但是,我得到列表中的所有项目都是相同的,并且等于最新收到的项目。显而易见,所有列表项都指向相同的内存地址,并且我想为每个调用该函数的用户获取一个新的内存地址。

clo*_*ker 7

python中“new”的等价物是只使用构造函数,例如:

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

由于您是从 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
Run Code Online (Sandbox Code Playgroud)

然而:

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']
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您可以预先分配大小,但在 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
Run Code Online (Sandbox Code Playgroud)

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

对于高效的矢量化操作(以及更低的内存占用),请使用 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
Run Code Online (Sandbox Code Playgroud)

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


Bas*_*tch 3

您应该阅读Python 教程

您可以在 Python 中创建列表、字典、对象和闭包。所有这些都位于(Python)堆中并且Python有一个简单的垃圾收集器(引用计数+循环标记)。

(Python GC 很幼稚,因为它不使用复杂的 GC 技术;因此它比 Ocaml 或许多 JVM 分代复制垃圾收集器慢;请阅读GC 手册了解更多信息;但是 Python GC 对外部 C 代码更友好)