gpt4 book ai didi

python - 内存使用量 : creating one big set vs merging many small sets

转载 作者:IT王子 更新时间:2023-10-28 23:35:51 26 4
gpt4 key购买 nike

我使用了%memit测量内存使用的魔术函数:

In [1]: %memit n = pow(10, 7); range(n)
peak memory: 568 MiB, increment: 272 MiB

In [2]: %memit n = pow(10, 7); set(xrange(n))
peak memory: 824 MiB, increment: 447 MiB

好的,所以似乎有一个中间步骤 xrange(n) 被实例化为一个完整的列表。但是,如果我将列表分成 10 个子列表,然后将它们一一合并呢?这样会更节省内存,对吧?

In [3]: %memit n = pow(10, 7); reduce(set.union, (set(xrange(p, n, 10)) for p in range(10)))
peak memory: 1260 MiB, increment: 897 MiB

嗯,这并没有按预期进行。为什么 reduce 方法比 set(xrange(n)) 消耗更多的内存?

最佳答案

Per the docs , reduce 大致相当于:

def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value

遍历iterable, (set(xrange(p, n, 10)) for p in range(10)),大约需要 447 MiB。你可能会认为,由于这个迭代器是一个生成器表达式,你会节省内存,但整数是 saved in an internal free list :

“For speed”, Python maintains an internal free list for integer objects. Unfortunately, that free list is both immortal and unbounded in size.

因此,一旦实例化了每个集合,它所消耗的大部分内存就永远不会被释放。

返回值 accum_value 也需要大约 447 MiB。因此,对 reduce 的调用总共需要大约 447+447 = 894 MiB。

关于python - 内存使用量 : creating one big set vs merging many small sets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32413224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com