while循环使用if语句比while循环更快

时间:2012-12-14 21:08:02

标签: python performance if-statement python-3.x while-loop

我正在测试循环中if语句的速度及其对速度的影响。我发现的东西始终如一,if语句提高了性能。我的代码:

import time
t = time.time

start = t()
x = 0
while x < 10000000:
    x += 1
time1 = t()
x = 0
while x < 10000000:
    x += 1
    if True:
        pass
time2 = t()

print(start)
print(time1 - start) # Time for simple while-loop
print(time2 - time1) # Time for while+if

示例输出将是:

1355517837.993
1.7850000858306885
1.7209999561309814

这完全违反直觉。 while-if-loop的工作速度比标准的while循环要快得多。几乎每次我运行时都会发生这种情况;也许每20次中有1次需要更长时间。有谁知道为什么?

2 个答案:

答案 0 :(得分:5)

显示循环时if语句有更多步骤。

In [4]: dis.dis(t2)
  2           0 LOAD_CONST               1 (0)
              3 STORE_FAST               0 (x)

  3           6 SETUP_LOOP              26 (to 35)
        >>    9 LOAD_FAST                0 (x)
             12 LOAD_CONST               2 (10000000)
             15 COMPARE_OP               0 (<)
             18 POP_JUMP_IF_FALSE       34

  4          21 LOAD_FAST                0 (x)
             24 LOAD_CONST               3 (1)
             27 INPLACE_ADD
             28 STORE_FAST               0 (x)
             31 JUMP_ABSOLUTE            9
        >>   34 POP_BLOCK
        >>   35 LOAD_CONST               0 (None)
             38 RETURN_VALUE

In [5]: dis.dis(t1)
  2           0 LOAD_CONST               1 (0)
              3 STORE_FAST               0 (x)

  3           6 SETUP_LOOP              35 (to 44)
        >>    9 LOAD_FAST                0 (x)
             12 LOAD_CONST               2 (10000000)
             15 COMPARE_OP               0 (<)
             18 POP_JUMP_IF_FALSE       43

  4          21 LOAD_FAST                0 (x)
             24 LOAD_CONST               3 (1)
             27 INPLACE_ADD
             28 STORE_FAST               0 (x)

  5          31 LOAD_GLOBAL              0 (True)
             34 POP_JUMP_IF_FALSE        9

  6          37 JUMP_ABSOLUTE            9
             40 JUMP_ABSOLUTE            9
        >>   43 POP_BLOCK
        >>   44 LOAD_CONST               0 (None)
             47 RETURN_VALUE

答案 1 :(得分:3)

我猜测编译器会删除if True块,因为它是常量。

当我跑步时,我得到的结果大多与你相反。我可能只是执行环境的随机效应。

1355519587.2 0.832797050476 1.04382395744

1355519590.03 0.863899946213 1.09347200394

1355519593.72 0.831655025482 1.05389809608

1355519599.71 0.831452131271 1.41783499718

1355519602.99 0.815280914307 1.05724310875

1355519605.72 0.826404094696 1.05700492859

1355519608.94 0.827296972275 1.07807898521