一個功能的實作,可以用多種語句來實作,比如說:while語句、for語句、生成器、清單推導、内置函數等實作,然而他們的效率并不一樣。寫了一個小程式來測試它們執行的效率。
測試内容:
将一個數字大小為20萬的數字,依次取絕對值,放到清單中,測試重複1千次.
測試程式:
- import time,sys
- reps = 1000 #測試重複次數
- nums = 200000 #測試時數字大小
- def tester(func,*args): #總體測試函數
- startTime = time.time()
- for i in range(reps):
- func(*args)
- elapsed = time.time() - startTime #用time子產品來測試,結束時間與開始時間差
- return elapsed
- def while_Statement(): #while循環實作
- res = []
- x = 0
- while nums > x:
- x += 1
- res.append(abs(x))
- def for_Statement(): #for循環實作
- for x in range(nums):
- def generator_Expression():#生成器實作
- res = list(abs(x) for x in range(nums))
- def list_Comprehension(): #清單解析實作
- res = [abs(x) for x in range(nums)]
- def map_Function(): #内置函數map實作
- res = map(abs, range(nums))
- print sys.version #列印系統版本
- tests = [while_Statement, for_Statement, generator_Expression, list_Comprehension, map_Function]
- for testfunc in tests: #将待測函數放置清單中依次周遊
- print testfunc.__name__.ljust(20),': ',tester(testfunc) #
測試結果:
- >>>
- 2.7.4 (default, Apr 6 2013, 19:55:15) [MSC v.1500 64 bit (AMD64)]
- while_Statement : 84.5769999027
- for_Statement : 75.2709999084
- generator_Expression : 62.3519999981
- list_Comprehension : 60.4090001583
- map_Function : 47.5629999638
- import sys
- nums = 100
- def while_Statement():
- def for_Statement():
- def generator_Expression():
- def list_Comprehension():
- def map_Function():
- if __name__=='__main__':
- import timeit #用timeit子產品來測試
- print sys.version
- funcs = [while_Statement, for_Statement, generator_Expression, list_Comprehension, map_Function]
- for func in funcs:
- print func.__name__.ljust(20),': ',timeit.timeit("func()", setup="from __main__ import func")
- while_Statement : 37.1800067428
- for_Statement : 30.3999109329
- generator_Expression : 27.2597866441
- list_Comprehension : 17.386223449
- map_Function : 12.7386868963
測試分析: