飘逸的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代码如下.
下面是使用dis来进行剖析.
根据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的指令相同,所以没有性能区别了.
使用超级简单: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的指令相同,所以没有性能区别了.
相关文章推荐
- 飘逸的python - 使用dis模块进行代码层次的性能剖析
- 使用 profile 进行python代码性能分析
- 在C/C++代码中使用SSE等指令集的指令(5)SSE进行加法运算简单的性能测试
- [有趣的Python 8]使用C模块来提高性能 [转]
- 在C/C++代码中使用SSE等指令集的指令(5)SSE进行加法运算简单的性能测试
- Python代码分析工具之dis模块
- 飘逸的python - 使用图像匹配SIFT算法进行LOGO检测
- 在C/C++代码中使用SSE等指令集的指令(5)SSE进行加法运算简单的性能测试
- Python札记 -- 使用easy_install进行模块/包管理
- Python性能提升一 —— 高计算模块使用C++编写
- Python札记 -- 使用easy_install进行模块/包管理
- 飘逸的python - 使用reload进行热更新
- 飘逸的python - 使用reload进行热更新
- 使用python进行编程.工具是次要的.关键在理解代码.
- 在cacti中使用ATS的stats_over_http模块进行监控部分性能
- 使用Python进行AES加密和解密的示例代码
- python re模块编译代码与非编译代码性能检测
- 在C/C++代码中使用SSE等指令集的指令(5)SSE进行加法运算简单的性能测试
- python使用xlrd模块对excel进行读取
- 使用python进行编程.工具是次要的.关键在理解代码.