Python 中 time 模組的 clock()和 time()方法

Vaibhav Vaibhav 2022年5月18日
Python 中 time 模組的 clock()和 time()方法

time 模組是 Python 標準庫的一部分。

該模組包含與時間相關的實用程式。該模組用於各種任務,例如計算程式碼塊的執行時間,將時間從一個單位轉換為另一個單位,例如小時到秒,天到毫秒,訪問掛鐘時間。

time 模組有兩種常用的方法,即 clock()time()。本文將討論 Python 的 time 模組的 clock()time() 方法。

Python 中 time 模組的 clock()time() 方法

time 模組的 clock() 方法返回自當前程序啟動以來的 CPU 時間或實時時間。

不幸的是,這種方法依賴於平臺。這意味著 clock() 方法對於基於 UNIX 的作業系統(例如 macOS、Linux 和 Microsoft Windows)的行為不同。

對於基於 UNIX 的系統,此方法將程序的 CPU 時間作為浮點數返回,並以秒為單位進行轉換。同時,Microsoft Windows 返回自第一次呼叫此方法以來經過的實際時間或掛鐘時間(以秒為單位)。

由於這種不平衡,clock() 方法已從 Python 3.8 的 time 模組中刪除。

time() 方法以浮點數返回當前時間(以秒為單位)。與 clock() 方法不同,time() 方法與平臺無關。

藉助示例讓我們知道它的用法。請參閱以下 Python 程式碼。

import time

start = time.time()
time.sleep(5)
end = time.time()
print(end - start)

輸出:

5.021177291870117

上面的 Python 程式碼首先呼叫 time() 函式並將時間戳儲存在一個變數中。

接下來,它使用 sleep() 方法休眠或等待 5 秒。然後,它再次呼叫 time() 函式並儲存時間戳。最後,它將時差列印到控制檯。

請注意,對我來說,時差是 5.021177291870117,非常接近 5。請記住,在計算中可以發現很小的變化。

執行 5 秒的睡眠動作以表示需要大約 5 秒才能完成的任務。它應該放在兩個 time() 方法呼叫之間,以測量程式碼塊的執行時間。

有關示例,請參閱以下 Python 程式碼。

import time

start = time.time()
s = 0

for i in range(100000000):
    s += i

print(s)
end = time.time()
print("Time Difference:", end - start)

輸出:

4999999950000000
Time Difference: 14.171791315078735
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相關文章 - Python Time