[英]why simple for loop with if condition is faster than conditional generator expression in python
Why is this for loop with if condition in first case is more than 2 times faster than second case with a conditional generator expression? 为什么带有条件生成器表达式的if条件在第一种情况下的for循环比第二种情况快2倍以上?
%%timeit
for i in range(100000):
if i < 10000:
continue
pass
clocks at 100 loops, best of 3: 2.85 ms per loop, while using generator expression: 在使用生成器表达式的情况下,时钟频率为100个循环,最好为3:每个循环2.85毫秒:
%%timeit
for i in (i for i in range(100000) if i >= 10000):
pass
100 loops, best of 3: 6.03 ms per loop 100次循环,最佳3:每个循环6.03毫秒
First version : For each element in range: assign it to i
. 第一版 :对于范围中的每个元素:将其分配给
i
。
Second version : For each element in range: assign it to inner i
(third one from the left), evaluate expression i
(the i
from ...(i for...
assign result to "outer" (leftmost) i
. 第二个版本 :对于范围内的每个元素:将其分配给内
i
(从左边第三个),评估表达i
(在i
从...(i for...
分配结果“外”(最左边) i
。
The if
statements have probably a similar performance impact in both versions. 在两个版本中,
if
语句可能会对性能产生类似的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.