在使用内存分析器进行分析时,输出如下:
102.632812 MiB 0.000000 MiB init()
236.765625 MiB 134.132812 MiB add_to_list()
return pd.DataFrame()
394.328125 MiB 157.562500 MiB pd_df = pd.DataFrame(pd_arr, columns=df_columns)
350.121094 MiB -44.207031 MiB pd_df = pd_df.set_index(df_columns[0])
350.292969 MiB 0.171875 MiB pd_df.memory_usage()
350.328125 MiB 0.035156 MiB print sys.getsizeof(pd_arr), sys.getsizeof(pd_arr[0]), sys.getsizeof(pd_df), len(pd_arr)
350.328125 MiB 0.000000 MiB del pd_arr
在检查pd_df(数据框)的深层内存使用情况时,它为80.5 MB。所以我的问题是,在del pd_arr
行之后,为什么内存没有减少。
此外,根据分析器的总数据框大小(157-44 = 110 MB),似乎比80 MB还多。那是什么导致了差异?
另外,是否有其他内存高效的方法来创建数据框(在循环中接收数据),而时间性能又不太差(例如:100MB大小的数据框增量应该在10秒左右)?
编辑:简单的Python脚本解释了这种行为
Filename: py_test.py
Line # Mem usage Increment Line Contents
================================================
9 102.0 MiB 0.0 MiB @profile
10 def setup():
11 global arr, size
12 102.0 MiB 0.0 MiB arr = range(1, size)
13 131.2 MiB 29.1 MiB arr = [x+1 for x in arr]
Filename: py_test.py
Line # Mem usage Increment Line Contents
================================================
21 131.2 MiB 0.0 MiB @profile
22 def tearDown():
23 global arr
24 131.2 MiB 0.0 MiB del arr[:]
25 131.2 MiB 0.0 MiB del arr
26 93.7 MiB -37.4 MiB gc.collect()
介绍DataFrame:
Filename: py_test.py
Line # Mem usage Increment Line Contents
================================================
9 102.0 MiB 0.0 MiB @profile
10 def setup():
11 global arr, size
12 102.0 MiB 0.0 MiB arr = range(1, size)
13 132.7 MiB 30.7 MiB arr = [x+1 for x in arr]
Filename: py_test.py
Line # Mem usage Increment Line Contents
================================================
15 132.7 MiB 0.0 MiB @profile
16 def dfCreate():
17 global arr
18 147.1 MiB 14.4 MiB pd_df = pd.DataFrame(arr)
19 147.1 MiB 0.0 MiB return pd_df
Filename: py_test.py
Line # Mem usage Increment Line Contents
================================================
21 147.1 MiB 0.0 MiB @profile
22 def tearDown():
23 global arr
24 #del arr[:]
25 147.1 MiB 0.0 MiB del arr
26 147.1 MiB 0.0 MiB gc.collect()
pd_arr
吗?Python 是基于引用计数的,所以使用del
只有在确保已删除的对象不会从任何地方使用时才能释放相关内存。你也可以尝试清空列表。 - jdehesadel pd_arr[:]
。没有减少内存。在代码中,pd_arr被定义为全局变量。这会有所不同吗? - Rajs123del pd_arr
只是意味着你不能再使用pd_arr
这个名称来引用那个列表了,无论是全局的还是局部的。但是,如果在之前的某个地方有类似a = pd_arr
的操作(尽管可能更加微妙,比如将pd_arr
传递给一个函数并在其他地方复制其引用),那么它实际上并没有被真正删除。然而,我无法解释为什么del pd_arr[:]
没有任何区别。 - jdehesa