天天看點

Python幾種語句執行效率問題

一個功能的實作,可以用多種語句來實作,比如說:while語句、for語句、生成器、清單推導、内置函數等實作,然而他們的效率并不一樣。寫了一個小程式來測試它們執行的效率。

測試内容: 

将一個數字大小為20萬的數字,依次取絕對值,放到清單中,測試重複1千次.

測試程式:

  1. import time,sys  
  2. reps = 1000                #測試重複次數  
  3. nums = 200000              #測試時數字大小  
  4. def tester(func,*args):    #總體測試函數  
  5.     startTime = time.time()  
  6.     for i in range(reps):  
  7.         func(*args)  
  8.     elapsed = time.time() - startTime #用time子產品來測試,結束時間與開始時間差  
  9.     return elapsed  
  10. def while_Statement():     #while循環實作  
  11.     res = []  
  12.     x   = 0  
  13.     while nums > x:  
  14.         x += 1  
  15.         res.append(abs(x))  
  16. def for_Statement():       #for循環實作  
  17.     for x in range(nums):  
  18. def generator_Expression():#生成器實作  
  19.     res = list(abs(x) for x in range(nums))  
  20. def list_Comprehension():  #清單解析實作  
  21.     res = [abs(x) for x in range(nums)]  
  22. def map_Function():        #内置函數map實作  
  23.     res = map(abs, range(nums))  
  24. print sys.version          #列印系統版本  
  25. tests = [while_Statement, for_Statement, generator_Expression, list_Comprehension, map_Function]  
  26. for testfunc in tests:     #将待測函數放置清單中依次周遊  
  27.     print testfunc.__name__.ljust(20),': ',tester(testfunc)  #  

測試結果:

  1. >>>   
  2. 2.7.4 (default, Apr  6 2013, 19:55:15) [MSC v.1500 64 bit (AMD64)]  
  3. while_Statement      :  84.5769999027  
  4. for_Statement        :  75.2709999084  
  5. generator_Expression :  62.3519999981  
  6. list_Comprehension   :  60.4090001583  
  7. map_Function         :  47.5629999638  
  1. import sys  
  2. nums = 100  
  3. def while_Statement():  
  4. def for_Statement():  
  5. def generator_Expression():  
  6. def list_Comprehension():  
  7. def map_Function():  
  8. if __name__=='__main__':  
  9.     import timeit            #用timeit子產品來測試  
  10.     print sys.version  
  11.     funcs = [while_Statement, for_Statement, generator_Expression, list_Comprehension, map_Function]  
  12.     for func in funcs:  
  13.         print func.__name__.ljust(20),': ',timeit.timeit("func()", setup="from __main__ import func")  
  1. while_Statement      :  37.1800067428  
  2. for_Statement        :  30.3999109329  
  3. generator_Expression :  27.2597866441  
  4. list_Comprehension   :  17.386223449  
  5. map_Function         :  12.7386868963  

測試分析: