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)文章
PyCharm2019.3永久激活破解詳細(xì)圖文教程,親測可用(不定期更新)
這篇文章主要介紹了PyCharm2019.3最新激活碼(注冊碼)破解永久版詳細(xì)圖文教程的相關(guān)資料,親測可用,需要的朋友可以參考下2020-10-10Python實現(xiàn)讀取并寫入Excel文件過程解析
這篇文章主要介紹了Python實現(xiàn)讀取并寫入Excel文件過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Linux下Pycharm、Anaconda環(huán)境配置及使用踩坑
這篇文章主要介紹了Linux下Pycharm、Anaconda環(huán)境配置及使用踩坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12Python實現(xiàn)在tkinter中使用matplotlib繪制圖形的方法示例
這篇文章主要介紹了Python實現(xiàn)在tkinter中使用matplotlib繪制圖形的方法,結(jié)合實例形式分析了Python使用tkinter與matplotlib進(jìn)行正弦曲線圖形繪制的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01基于Python pyecharts實現(xiàn)多種圖例代碼解析
這篇文章主要介紹了基于Python pyecharts實現(xiàn)多種圖例代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08使用pycallgraph分析python代碼函數(shù)調(diào)用流程以及框架解析
這篇文章主要介紹了使用pycallgraph分析python代碼函數(shù)調(diào)用流程以及框架解析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03