python計算程序運行時間


內置模塊time包含很多與時間相關函數。我們可通過它獲得當前的時間和格式化時間輸出。

time(),以浮點形式返回自Linux新世紀以來經過的秒數。在linux中,00:00:00 UTC, January 1, 1970是新**49**的開始。

import time

start = time.clock()

#當中是你的程序

elapsed = (time.clock() - start)
print("Time used:",elapsed)


或者:
from time import time

def timeTest():
    start = time()
    print("Start: " + str(start))
    for i in range(1, 100000000):
        pass
    stop = time()
    print("Stop: " + str(stop))
    print(str(stop-start) + "")

def main():
    timeTest()

if __name__=='__main__':
    main()

Python:time.clock() vs. time.time()

作者 Ross Wan on 2008/09/19

有時候,我們需要知道程序或者當中的一段代碼的執行速度,於是就會加入一段計時的代碼,如下:

start = time.clock()
... do something
elapsed = (time.clock() - start)

又或者

start = time.time()
... do something
elapsed = (time.time() - start)

那究竟 time.clock() 跟 time.time(),誰比較精確呢?帶着疑問,查了 Python 的 time 模塊文檔,當中 clock() 方法有這樣的解釋:

clock()

On
Unix, return the current processor time as a floating point number
expressed in seconds. The precision, and in fact the very definition of
the meaning of “processor time”, depends on that of the C function of
the same name, but in any case, this is the function to use for
benchmarking Python or timing algorithms.

On Windows, this
function returns wall-clock seconds elapsed since the first call to
this function, as a floating point number, based on the Win32 function
QueryPerformanceCounter(). The resolution is typically better than one
microsecond.

可見,time.clock() 返回的是處理器時間,而因為 Unix 中 jiffy 的緣故,所以精度不會太高。clock轉秒,除以1000000。

總結

究竟是使用 time.clock() 精度高,還是使用 time.time() 精度更高,要視乎所在的平台來決定。總概來講,在 Unix 系統中,建議使用 time.time(),在 Windows 系統中,建議使用 time.clock()。

這個結論也可以在 Python 的 timtit 模塊中(用於簡單測量程序代碼執行時間的內建模塊)得到論證:

if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time

使用 timeit 代替 time,這樣就可以實現跨平台的精度性:

start = timeit.default_timer()
... do something
elapsed = (timeit.default_timer() - start)


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM