【发布时间】:2018-06-01 07:05:57
【问题描述】:
首先,我想测试生成器和列表理解之间的内存使用情况。这本书给了我一个小台代码sn-p,我在我的PC(python3.6,Windows)上运行它,发现了一些意想不到的东西。
- 书上说,因为列表理解必须创建一个真正的列表并为其分配内存,所以从列表理解中迭代必须比从生成器中迭代慢。
- 当然,列表理解比生成器使用更多内存。
以下是我的代码,不满足先前的意见(在 sum 函数内)。
import tracemalloc
from time import time
def timeIt(func):
start = time()
func()
print('%s use time' % func.__name__, time() - start)
return func
tracemalloc.start()
numbers = range(1, 1000000)
@timeIt
def lStyle():
return sum([i for i in numbers if i % 3 == 0])
@timeIt
def gStyle():
return sum((i for i in numbers if i % 3 == 0))
lStyle()
gStyle()
shouldSize = [i for i in numbers if i % 3 == 0]
snapshotL = tracemalloc.take_snapshot()
top_stats = snapshotL.statistics('lineno')
print("[ Top 10 ]")
for stat in top_stats[:10]:
print(stat)
输出:
lStyle use time 0.4460000991821289
gStyle use time 0.6190001964569092
[ Top 10 ]
F:/py3proj/play.py:31: size=11.5 MiB, count=333250, average=36 B
F:/py3proj/play.py:33: size=448 B, count=1, average=448 B
F:/py3proj/play.py:22: size=136 B, count=1, average=136 B
F:/py3proj/play.py:17: size=136 B, count=1, average=136 B
F:/py3proj/play.py:14: size=76 B, count=2, average=38 B
F:/py3proj/play.py:8: size=34 B, count=1, average=34 B
两点:
- 生成器使用更多的时间和相同的内存空间。
- sum 函数中的列表理解似乎无法创建总列表
我想也许 sum 函数做了一些我不知道的事情。谁能解释一下?
这本书是 High Perfoamance Python.chapter 5.But I do sth own different from the book to check the evidence in other context.他的代码在这里book_code,他没有把列表理解放在 sum 函数中。
【问题讨论】:
-
你正在针对一个列表测试一个元组,没有生成器
-
@EvgenyPogrebnyak 没有元组理解之类的东西,括号中的生成器表达式是生成器表达式。参见例如stackoverflow.com/q/16940293/3001761.
-
我错了!
type((x for x in [1,2,3]))确实是一个生成器 -
我认为你应该说是哪本书告诉你的。
-
好的,我补充一下@BoarGules
标签: python sum generator python-internals