【发布时间】:2016-09-06 11:55:35
【问题描述】:
问题
假设我想为所有小于20000000 的数字找到n**2。
我测试的所有三个变体的常规设置:
import time, psutil, gc
gc.collect()
mem_before = psutil.virtual_memory()[3]
time1 = time.time()
# (comprehension, generator, function)-code comes here
time2 = time.time()
mem_after = psutil.virtual_memory()[3]
print "Used Mem = ", (mem_after - mem_before)/(1024**2) # convert Byte to Megabyte
print "Calculation time = ", time2 - time1
计算这些数字的三个选项:
1.创建通过理解的列表:
x = [i**2 for i in range(20000000)]
真的很慢很耗时:
Used Mem = 1270 # Megabytes
Calculation time = 33.9309999943 # Seconds
2。使用'()' 创建生成器:
x = (i**2 for i in range(20000000))
它比选项 1 快得多,但仍然占用大量内存:
Used Mem = 611
Calculation time = 0.278000116348
3.定义生成器函数(最有效):
def f(n):
i = 0
while i < n:
yield i**2
i += 1
x = f(20000000)
它的消耗:
Used Mem = 0
Calculation time = 0.0
问题是:
- 第一种和第二种解决方案有什么区别?使用
()会创建一个生成器,为什么它需要大量内存? - 是否有与我的第三个选项等效的内置函数?
【问题讨论】:
-
在 2.7 中使用
xrange以减少内存使用量。 -
就是这样 -
range在 Python 2.x 中无论如何都会创建一个列表。见What is the difference between range and xrange functions in Python 2.X? -
() need a lot of memory。这种说法大错特错。 -
@AKS 两个字节曾经被认为是很多:P
-
@Jules 确实如此!它
used to be:)
标签: python python-2.7 generator