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

他們都可以把 x 變成一個(gè)布爾類型的值:
>>> x = 123 >>> not not x True >>> bool(x) True >>>
那么誰(shuí)更快呢?我們寫段代碼,跑個(gè) 100 萬(wàn)次,來(lái)比較下誰(shuí)更快:
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()
運(yùn)行結(jié)果如下:

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

bool(x) 多了 LOAD_GLOBAL 和 CALL_FUNCTION。
這里附一下相關(guān)字節(jié)碼的官方說(shuō)明:
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é)果來(lái)看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一個(gè)函數(shù)調(diào)用,函數(shù)調(diào)用需要參數(shù)壓入棧頂,堆棧的頂部包含位置參數(shù),最右邊的參數(shù)在頂部,參數(shù)下面是要調(diào)用的可調(diào)用對(duì)象。CALL_FUNCTION 從堆棧中彈出所有參數(shù)和可調(diào)用對(duì)象,使用這些參數(shù)調(diào)用可調(diào)用對(duì)象,并推送可調(diào)用對(duì)象返回的返回值,這一過程比一個(gè) not 指令要慢得多。
不過我仍然推薦你使用 bool(x) ,因?yàn)樗目勺x性更高,而且,我們也不太可能調(diào)用它 100萬(wàn)次。
到此這篇關(guān)于python中not not x?與 bool(x) 的區(qū)別的文章就介紹到這了,更多相關(guān)not not x與bool(x) 的區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python創(chuàng)建Excel的4種方式小結(jié)
這篇文章主要為大家詳細(xì)介紹了Python中創(chuàng)建Excel的4種常見方式,文中的示例代碼簡(jiǎn)潔易懂,具有一定的參考價(jià)值,感興趣的小伙伴可以學(xué)習(xí)一下2025-02-02
詳解K-means算法在Python中的實(shí)現(xiàn)
這篇文章主要介紹了詳解K-means算法在Python中的實(shí)現(xiàn),具有一定借鑒價(jià)值,需要的朋友可以了解下。2017-12-12
Python機(jī)器學(xué)習(xí)應(yīng)用之工業(yè)蒸汽數(shù)據(jù)分析篇詳解
本篇文章介紹了如何用Python進(jìn)行工業(yè)蒸汽數(shù)據(jù)分析的過程及思路,通讀本篇對(duì)大家的學(xué)習(xí)或工作具有一定的價(jià)值,需要的朋友可以參考下2022-01-01
Python 標(biāo)準(zhǔn)庫(kù)zipfile將文件夾加入壓縮包的操作方法
Python zipfile 庫(kù)可用于壓縮/解壓 zip 文件. 本文介紹一下如何創(chuàng)建壓縮包,對(duì)Python zipfile壓縮包相關(guān)知識(shí)感興趣的朋友一起看看吧2021-09-09

