python中not not x 與bool(x) 的區(qū)別

他們都可以把 x 變成一個布爾類型的值:
>>> x = 123 >>> not not x True >>> bool(x) True >>>
那么誰更快呢?我們寫段代碼,跑個 100 萬次,來比較下誰更快:
import timeit
def bool_convert(x):
return bool(x)
def notnot_convert(x):
return not not x
def main():
trials = 10_000_000
kwargs = {
"setup": "x=42",
"globals": globals(),
"number": trials,
}
notnot_time = timeit.timeit("notnot_convert(x)", **kwargs)
bool_time = timeit.timeit("bool_convert(x)", **kwargs)
print(f"{bool_time = :.04f}")
print(f"{notnot_time = :.04f}")
if __name__ == "__main__":
main()
運行結(jié)果如下:

其實 bool(x) 慢的原因在于它是一個函數(shù)調(diào)用,而 not not x 就是一條指令,具有更快捷的轉(zhuǎn)換為布爾值的路徑,這一點可以從字節(jié)碼可以看出來:

bool(x) 多了 LOAD_GLOBAL 和 CALL_FUNCTION。
這里附一下相關(guān)字節(jié)碼的官方說明:
LOAD_GLOBAL(namei) Loads the global named co_names[namei] onto the stack. CALL_FUNCTION(argc) Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. UNARY_NOT Implements TOS = not TOS.
最后:
從結(jié)果來看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一個函數(shù)調(diào)用,函數(shù)調(diào)用需要參數(shù)壓入棧頂,堆棧的頂部包含位置參數(shù),最右邊的參數(shù)在頂部,參數(shù)下面是要調(diào)用的可調(diào)用對象。CALL_FUNCTION 從堆棧中彈出所有參數(shù)和可調(diào)用對象,使用這些參數(shù)調(diào)用可調(diào)用對象,并推送可調(diào)用對象返回的返回值,這一過程比一個 not 指令要慢得多。
不過我仍然推薦你使用 bool(x) ,因為它的可讀性更高,而且,我們也不太可能調(diào)用它 100萬次。
到此這篇關(guān)于python中not not x?與 bool(x) 的區(qū)別的文章就介紹到這了,更多相關(guān)not not x與bool(x) 的區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python創(chuàng)建Excel的4種方式小結(jié)
這篇文章主要為大家詳細介紹了Python中創(chuàng)建Excel的4種常見方式,文中的示例代碼簡潔易懂,具有一定的參考價值,感興趣的小伙伴可以學(xué)習(xí)一下2025-02-02
Python機器學(xué)習(xí)應(yīng)用之工業(yè)蒸汽數(shù)據(jù)分析篇詳解
本篇文章介紹了如何用Python進行工業(yè)蒸汽數(shù)據(jù)分析的過程及思路,通讀本篇對大家的學(xué)習(xí)或工作具有一定的價值,需要的朋友可以參考下2022-01-01
Python 標準庫zipfile將文件夾加入壓縮包的操作方法
Python zipfile 庫可用于壓縮/解壓 zip 文件. 本文介紹一下如何創(chuàng)建壓縮包,對Python zipfile壓縮包相關(guān)知識感興趣的朋友一起看看吧2021-09-09

