自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Not not x 和 Bool(x) 用哪個比較好?

開發(fā) 前端
從結(jié)果來看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一個函數(shù)調(diào)用,函數(shù)調(diào)用需要參數(shù)壓入棧頂,堆棧的頂部包含位置參數(shù),最右邊的參數(shù)在頂部,參數(shù)下面是要調(diào)用的可調(diào)用對象。

[[434453]]

今天來做一個選擇,就是 not not x 和 bool(x) 用哪個比較好?

他們都可以把 x 變成一個布爾類型的值:

  1. >>> x = 123 
  2. >>> not not x 
  3. True 
  4. >>> bool(x) 
  5. True 
  6. >>> 

那么誰更快呢?我們寫段代碼,跑個 100 萬次,來比較下誰更快:

  1. import timeit 
  2.  
  3.  
  4. def bool_convert(x): 
  5.     return bool(x) 
  6.  
  7.  
  8. def notnot_convert(x): 
  9.     return not not x 
  10.  
  11.  
  12. def main(): 
  13.     trials = 10_000_000 
  14.     kwargs = { 
  15.         "setup""x=42"
  16.         "globals": globals(), 
  17.         "number": trials, 
  18.     } 
  19.  
  20.     notnot_time = timeit.timeit("notnot_convert(x)", **kwargs) 
  21.     bool_time = timeit.timeit("bool_convert(x)", **kwargs) 
  22.  
  23.     print(f"{bool_time = :.04f}"
  24.     print(f"{notnot_time = :.04f}"
  25.  
  26.  
  27. if __name__ == "__main__"
  28.     main() 

運(yùn)行結(jié)果如下:

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

bool(x) 多了 LOAD_GLOBAL 和 CALL_FUNCTION。

這里附一下相關(guān)字節(jié)碼的官方說明:

  1. LOAD_GLOBAL(namei) 
  2. Loads the global named co_names[namei] onto the stack. 
  3.  
  4. CALL_FUNCTION(argc) 
  5. 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. 
  6.  
  7. UNARY_NOT 
  8. 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),因?yàn)樗目勺x性更高,而且,你也不太可能調(diào)用它 100萬次。

 

責(zé)任編輯:武曉燕 來源: Python七號
相關(guān)推薦

2021-11-05 07:13:46

Python

2021-11-30 23:01:51

編程語言數(shù)據(jù)Python

2009-09-15 09:24:42

思科認(rèn)證考試思科認(rèn)證

2021-08-05 08:32:45

TypeScript InterfaceType

2020-09-23 16:53:46

Python編輯器工具

2018-06-16 14:32:16

無線路由器單頻雙頻

2021-03-15 14:09:49

電腦軟件安全

2010-03-29 17:38:18

CentOS源代碼

2020-01-17 13:33:42

大數(shù)據(jù)分析師大數(shù)據(jù)工程師

2011-10-26 20:34:24

ssh 客戶端

2020-11-18 09:26:52

@property裝飾器代碼

2020-07-28 10:40:26

大數(shù)據(jù)專業(yè)技術(shù)

2020-12-08 15:54:15

編程語言Python

2015-01-08 22:06:18

2020-06-30 09:10:35

編程學(xué)習(xí)技術(shù)

2023-04-27 07:26:31

IP地址無符號

2022-06-06 15:06:42

MySQLJAVA

2018-12-17 13:03:39

AI數(shù)據(jù)科技

2014-06-05 15:16:49

Linux開源Flash
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號