您的位置:首页 > 编程语言 > Python开发

飘逸的python - 使用dis模块进行代码层次的性能剖析

2014-11-25 12:22 686 查看
dis — Disassembler for Python bytecode,即把python代码反汇编为字节码指令.

使用超级简单: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.

The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators.

可以看到,在while 1这里(第3行),直接是JUMP_ABSOLUTE指令;
而while True这里(第5行),由LOAD_NAME和POP_JUMP_IF_FALSE指令组成.

原来True在python2中不是一个关键字,只是一个内置的变量,bool类型,值为1,即True+True输出2.

而且还可以被赋值.比如赋值True = 2, 甚至可以赋值True = False.
所以while True的时候, 每次循环都要检查True的值, 对应指令LOAD_NAME.

这就是为什么while True比while 1慢了.

不过在python3中,True变成了关键字了.while 1和while True的指令相同,所以没有性能区别了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: