飄逸的python - 使用dis模塊進行代碼層次的性能剖析

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:

  1. the line number, for the first instruction of each line
  2. the current instruction, indicated as -->,
  3. a labelled instruction, indicated with >>,
  4. the address of the instruction,
  5. the operation code name,
  6. operation parameters, and
  7. 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的指令相同,所以沒有性能區別了.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章