今天,不僅在有限的資源中完成一個項目非常重要,而且在盡可能短的時間內完成它也很重要。我們有time()
Python中計算代碼執行時間的函數。
當我們執行任何代碼時,會發生幾個後台操作來執行我們的代碼執行。什麽時候time()
函數計算它不考慮執行此代碼的後台操作的時間。此外,我們減去開始和結束的時間以獲得所需的時間。現在已經開發了 timeit() 函數來查找任何特定代碼執行的確切時間。甚至它依靠一毫秒的 0.0000 個小數點的計時來找到 cod 執行中的準確計時。在這裏我們將看到這個函數是如何工作的。
timeit() 函數的代碼執行示例:
我們將輸入python
並按回車鍵。您會像我們使用的python和Microsoft版本一樣做出響應。此外,它確認我們正在使用 python 工作。
導入聲明:
import timeit
如果您收到類似 'import' 未定義的響應,請檢查係統變量是否已更新。
現在,我們將編寫一個簡單的數學運算,並通過兩種方法找到它的執行時間。
# python example to demonstrate the
# example of timeit() function
# importing the module
import timeit
# operations and time calcuation
print('a' *5)
print('a' + 'a' +'a' + 'a' + 'a' )
print(timeit.timeit("b = 'a' *3",number = 10000000))
輸出
aaaaa aaaaa 0.9088429469993571
在這裏,您可以將 number 的值設置為所需的代碼執行次數的任意次數。
import timeit
print(timeit.timeit("ab = 'a' + 'a' + 'a' + 'a' + 'a' ", number=10000000))
輸出
0.8887228329986101
該方法描述了手動查找執行時間的方法。在這裏手動意味著我們必須多次執行整個操作。
帶例子的自動重複方法
現在我們將看到如何自動執行同樣繁瑣的操作?
import timeit
print(timeit.repeat("b = 'a'* 3", number = 10000000,repeat = 5))
print()
print(timeit.repeat("ab = 'a' + 'a' + 'a' + 'a' + 'a' " , number = 10000000,repeat = 5))
輸出
[0.8862817650006036, 0.8274680489994353, 0.891247380997811, 0.9186934919998748, 0.900538891000906] [0.8854398910043528, 0.8779188379994594, 0.8196939810004551, 0.8731913320007152, 0.8250786080025136]
在這裏我們可以看到重複自動發生了很多次。
為什麽是 timeit()?
timeit() 函數因其準確性而成為尋找執行時間的最佳選擇,而不是時間函數。我們關於 time() 函數中代碼執行的許多假設都是錯誤的,這在 timeit() 函數中得到糾正,例如考慮到後台操作所花費的時間。同理,timeit() 也是尋找執行時機的更寶貴、最短的路徑。
相關用法
- Python time.monotonic()用法及代碼示例
- Python time.asctime()用法及代碼示例
- Python time.clock()用法及代碼示例
- Python time.ctime()用法及代碼示例
- Python time.perf_counter()用法及代碼示例
- Python time.get_clock_info()用法及代碼示例
- Python time.gmtime()用法及代碼示例
- Python time.time()用法及代碼示例
- Python time.mktime()用法及代碼示例
- Python time.sleep()用法及代碼示例
- Python time.clock_gettime_ns()用法及代碼示例
- Python time.process_time_ns()用法及代碼示例
- Python time.monotonic_ns()用法及代碼示例
- Python time.time_ns()用法及代碼示例
- Python timedelta total_seconds()用法及代碼示例
- Python time.strftime()用法及代碼示例
- Python time.clock_getres()用法及代碼示例
- Python time.clock_settime()用法及代碼示例
- Python time.process_time()用法及代碼示例
- Python time.localtime()用法及代碼示例
注:本文由純淨天空篩選整理自 timeit() Function with Example in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。