【发布时间】:2015-07-18 16:34:30
【问题描述】:
目前我正在学习生成器和列表理解,并在使用探查器以查看性能提升时偶然发现了这个 cProfile,该 cProfile 是使用两者的大范围内的素数之和。
我可以看到在生成器中 :1 基因expr 的累积时间比它的列表对应物要短,但是第二行让我感到困惑。正在做一个电话,我认为检查数字是素数,但不应该是列表理解中的另一个 :1 模块?
我是否遗漏了个人资料中的某些内容?
In [8]: cProfile.run('sum((number for number in xrange(9999999) if number % 2 == 0))')
5000004 function calls in 1.111 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
5000001 0.760 0.000 0.760 0.000 <string>:1(<genexpr>)
1 0.000 0.000 1.111 1.111 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.351 0.351 1.111 1.111 {sum}
In [9]: cProfile.run('sum([number for number in xrange(9999999) if number % 2 == 0])')
3 function calls in 1.123 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.075 1.075 1.123 1.123 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.048 0.048 0.048 0.048 {sum}
【问题讨论】:
-
我不认为他们是素数,只有偶数。
-
你为什么期待另一个
:1 module? -
一个函数调用比另一个函数调用多 5000001 次,这难道不是令人惊讶的事情吗?这正是
next被调用的次数。 -
在 Python 2 中你不会得到任何额外的列表解析行,但在 Python 3 中你会因为现在使它类似于生成器表达式一个额外的代码对象(
<listcomp>)也是为列表理解创建的:stackoverflow.com/a/30097520/846892 -
是的,对不起。我的意思是甚至。大脑冻结。 :D
标签: python profiling generator list-comprehension