Python time clock() 方法



Python 的 clock() 方法用於獲取當前處理器時間。它以秒為單位返回一個浮點數。如果要計算執行程式所需的時間,則需要隨後呼叫該方法。它們之間的差值被視為程式執行所需的時間。

此方法與平臺相關;在 Unix 上,當前處理器時間以秒為單位表示。精度取決於同名 C 函式的精度,但在任何情況下,此函式都是用於對 Python 或演算法進行基準測試或計時。

Windows 上,此函式基於 Win32 函式 QueryPerformanceCounter 返回自第一次呼叫此函式以來經過的掛鐘秒數,以浮點數表示。

注意:並非所有系統都能測量真實的程序時間。在這些系統(包括 Windows)上,clock 通常測量程式啟動以來的掛鐘時間。在 3.3 之後的 Python 版本中,此程式已棄用。

語法

以下是 Python clock() 方法的語法:

time.clock()

引數

該方法不接受任何引數。

返回值

此方法以秒為單位返回一個浮點數,表示當前處理器時間。

示例

以下示例演示了 Python clock() 方法的使用。我們只是使用此方法獲取程序時間。此示例僅可在 Python 2 中執行。

import time

tm = time.clock()

print "Process time:", tm

當我們執行上述程式時,它會產生以下結果:

Process time: 0.016222

示例

Python time clock() 方法獲取程序時間;並且您可能已經知道,程序時間與掛鐘時間不同。兩者不要混淆。

在此示例中,我們比較了此方法和 time() 方法的返回值。此方法返回程序時間,而 time() 方法返回掛鐘時間。此示例僅可在 Python 2 中執行。

import time

def procedure():
   time.sleep(2.5)

# measure process time
t0 = time.clock()
procedure()
print time.clock(), "seconds process time"

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"

讓我們比較一下

0.0 seconds process time
2.50023603439 seconds wall time

示例

如果要檢索執行程式所需的時間,則需要隨後呼叫 clock() 方法。

在以下示例中,我們在程式開始和結束時呼叫此方法,這兩個時間戳之間的差值將是程式執行所需的時間。同樣,這僅可在 Python 2 中執行。

import time

# Record the start process time
start = time.clock()
print "Starting process time:", start

# Performing addition task
i = 20
a = i + 30
print "Task:", a

# Ending process time
end = time.clock()
print "Ending process time:", end

print "Total amount of time taken:", (start-end)

上述程式的輸出為:

Starting process time: 0.015982
Task: 50
Ending process time: 0.016011
Total amount of time taken: -2.9e-05
python_date_time.htm
廣告