使用超級簡單: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慢了.