由关键字引发的速度差异

问题: while 1 与 while True 谁运行更快?

结论:

  • 分情况:
  • Python2 while 1 比 while True 快
  • Python3 因为True被作为关键字,所以一样快

分析:

  • 由于Python2中 True 不作为关键字,作为全局变量存在,需要一步加载到堆栈的操作LOAD_GLOBAL
  • 经过在同等条件下不严格测试,10分钟内 Python2使用 "while 1" 比 "while True" 多5亿次累加运算。
时间 True 1
60 sec 398419371 444008443
600 sec 3884225688 4450119584
  • 随着Python2 退出逐渐退出历史舞台,应当使用Python3, 可以不用再顾忌此类问题。

验证:

  • python2:
>>> def f():
...     while 1:
...             pass
... 
>>> import dis
>>> dis.dis(f)
  2           0 SETUP_LOOP               4 (to 7)

  3     >>    3 JUMP_ABSOLUTE            3
              6 POP_BLOCK           
        >>    7 LOAD_CONST               0 (None)
             10 RETURN_VALUE        
>>> def f():
...     while True:
...             pass
... 
>>> dis.dis(f)
  2           0 SETUP_LOOP              10 (to 13)
        >>    3 LOAD_GLOBAL              0 (True)
              6 POP_JUMP_IF_FALSE       12

  3           9 JUMP_ABSOLUTE            3
        >>   12 POP_BLOCK           
        >>   13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        
  • python3:
>>> import dis
>>> dis.dis(f)
  2           0 SETUP_LOOP               4 (to 7)

  3     >>    3 JUMP_ABSOLUTE            3
              6 POP_BLOCK

  4     >>    7 SETUP_LOOP               4 (to 14)

  5     >>   10 JUMP_ABSOLUTE           10
             13 POP_BLOCK
        >>   14 LOAD_CONST               0 (None)
             17 RETURN_VALUE
>>> def f():
...     while 1:
...             pass
... 
>>> dis.dis(f)
  2           0 SETUP_LOOP               4 (to 7)

  3     >>    3 JUMP_ABSOLUTE            3
              6 POP_BLOCK
        >>    7 LOAD_CONST               0 (None)
             10 RETURN_VALUE
>>> True = 1
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> 
KeyboardInterrupt
>>> def f():
...     while True:
...             pass
... 
>>> dis.dis(f)
  2           0 SETUP_LOOP               4 (to 7)

  3     >>    3 JUMP_ABSOLUTE            3
              6 POP_BLOCK
        >>    7 LOAD_CONST               0 (None)
             10 RETURN_VALUE
发布时间:
2017-06-20 19:55
分类:
标签: