简体   繁体   English

为什么简单的for循环,如果条件比python中的条件生成器表达式快

[英]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.

相关问题 生成器比python中的while循环快吗? - Is generator faster than while loop in python? Python 基准测试:为什么 for in loop 比简单的 while 更快? - Python benchmark: Why for in loop is faster than simple while? 为什么“in”生成器比python中的“in”列表快得多 - why "in" generator is much faster than "in" list in python 为什么求和列表理解比生成器表达式更快? - Why is summing list comprehension faster than generator expression? 为什么这个列表理解比等效的生成器表达更快? - Why this list comprehension is faster than equivalent generator expression? 为什么“不”运算符比 python 中的常规条件更快? - Why “not” operator is faster than regular condition in python? Python的[ <generator expression> ]比列表快至少3倍( <generator expression> )? - Python's [<generator expression>] at least 3x faster than list(<generator expression>)? Python:为什么一个生成器在内部具有“ yield”的情况下比其他生成器快? - Python: why is one generator faster than other with `yield` inside? 为什么count()方法比for循环python更快 - Why count() method is faster than a for loop python 为什么 PHP7 在执行这个简单循环时比 Python3 快得多? - Why is PHP7 so much faster than Python3 in executing this simple loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM