dis — Disassembler for Python bytecode,即把python代码反汇编为字节码指令.
使用超级简单:python -m dis xxx.py
当我在网上看到while 1比while True快的时候,我感到很困惑,为何会有这种区别呢?
而且还可以被赋值.比如赋值True = 2, 甚至可以赋值True = False.
使用超级简单:python -m dis xxx.py
当我在网上看到while 1比while True快的时候,我感到很困惑,为何会有这种区别呢?
于是使用dis来深入.
假设est_while.py代码如下.
#coding=utf-8
while 1:
pass
while True:
pass
下面是使用dis来进行剖析.
E:\>python -m dis test_while.py
2 0 SETUP_LOOP 3 (to 6)
3 >> 3 JUMP_ABSOLUTE 3
5 >> 6 SETUP_LOOP 10 (to 19)
>> 9 LOAD_NAME 0 (True)
12 POP_JUMP_IF_FALSE 18
根据python官方文档,dis输出报告的格式如下.
The output is divided in the following columns:
- the line number, for the first instruction of each line
- the current instruction, indicated as -->,
- a labelled instruction, indicated with >>,
- the address of the instruction,
- the operation code name,
- operation parameters, and
- interpretation of the parameters in parentheses.
而while True这里(第5行),由LOAD_NAME和POP_JUMP_IF_FALSE指令组成.
而且还可以被赋值.比如赋值True = 2, 甚至可以赋值True = False.
所以while True的时候, 每次循环都要检查True的值, 对应指令LOAD_NAME.
这就是为什么while True比while 1慢了.
本文通过对比while True与while 1的字节码指令差异,解释了两者在Python 2中的性能区别。并介绍了如何使用dis模块进行代码反汇编,最后说明了Python 3对此进行了改进。
391

被折叠的 条评论
为什么被折叠?



