简单的硬编码算法 cached/compiled 消失了吗?
Are simple hardcoded arithmetics cached/compiled away?
我想知道 python 是否在其 .pyc 文件中缓存/编译了简单的算法,例如 5*5+5
。
有时候我喜欢写if seconds > 24*60*60
一天。我知道对性能的影响并不明显,但我还是很好奇。
是的,CPython(Python的默认实现)使用了peephole optimiser to collapse such expressions into one number; this is called constant folding.
您可以使用 dis
disassembler:
检查这一点
>>> import dis
>>> def foo():
... if seconds > 24*60*60:
... pass
...
>>> dis.dis(foo)
2 0 LOAD_GLOBAL 0 (seconds)
3 LOAD_CONST 4 (86400)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 15
3 12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
注意偏移量 3 处的 LOAD_CONST
指令;它加载 24*60*60
表达式的最终结果,表达式本身从字节码中消失了。
我想知道 python 是否在其 .pyc 文件中缓存/编译了简单的算法,例如 5*5+5
。
有时候我喜欢写if seconds > 24*60*60
一天。我知道对性能的影响并不明显,但我还是很好奇。
是的,CPython(Python的默认实现)使用了peephole optimiser to collapse such expressions into one number; this is called constant folding.
您可以使用 dis
disassembler:
>>> import dis
>>> def foo():
... if seconds > 24*60*60:
... pass
...
>>> dis.dis(foo)
2 0 LOAD_GLOBAL 0 (seconds)
3 LOAD_CONST 4 (86400)
6 COMPARE_OP 4 (>)
9 POP_JUMP_IF_FALSE 15
3 12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
注意偏移量 3 处的 LOAD_CONST
指令;它加载 24*60*60
表达式的最终结果,表达式本身从字节码中消失了。