Dis-disassembler for Python bytecode, that is, the Python code is disassembled into bytecode instructions.
Super easy to use:
python-m Dis xxx.py
When I saw on the internet that while 1 was faster than while, I was confused and why was there such a difference?
Then use dis to go deep.
Suppose the est_while.py code is as follows.
#coding =utf-8while 1: passwhile True: Pass
The following is an analysis using DIS.
e:\>python-m dis test_while.py 2 0 setup_loop 3 (to 6) 3 >> 3 Jump_absolute 3 5 >> 6 setup_loop (to) >> 9 load_name 0 (True) Pop_jump_ If_false 18
According to the official Python documentation, the DIS output report is in the following format.
The output is divided in the following columns:
- The line number, for the first instruction
- 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 oper Ators.
As you can see, in the while 1 here (line 3rd), Direct is the jump_absolute instruction;
And while true here (line 5th) consists of load_name and pop_jump_if_false directives.
Original true in Python2 is not a keyword, just a built-in variable, bool type, the value is 1, that is, true+true output 2.
It can also be assigned value. For example, the assignment is true = 2 and can even be assigned a value of true = False.
So while true, each loop is checked for a value of true, corresponding to the instruction Load_name.
This is why while true is slower than while 1.
In Python3, however, true becomes the keyword. While 1 and while true have the same instructions, there is no performance difference.
Elegant Python-Profiling the code hierarchy using the DIS module