Categories: Python

Python 測量程式碼執行時間教學與範例

介紹如何使用 Python 的 timetimeitdatetime 模組測量程式執行時間。

time 模組

time 是 Python 標準的時間模組,其 time.time() 函數可以用來取得目前的時間戳記,藉由程式碼執行前後的時間戳記,就可以計算程式執行的時間:

# 引入 time 模組
import time

# 開始測量
start = time.time()

# 要測量的程式碼
for i in range(10000):
    "-".join(str(n) for n in range(100))

# 結束測量
end = time.time()

# 輸出結果
print("執行時間:%f 秒" % (end - start))
執行時間:0.440730 秒

由於 time.time() 所取得的是實際的時間戳記,所以最後算出來的時間是 wall-clock time,也就是說如果電腦上有很多其他的程式也同時在執行,這個時間算出來就會比較長。

如果不想讓計算結果受到其他程式的影響,可以改用 time.process_time(),用法差不多,不過他會以 CPU time 來計算:

# 引入 time 模組
import time

# 開始測量
start = time.process_time()

# 要測量的程式碼
for i in range(10000):
    "-".join(str(n) for n in range(100))

# 結束測量
end = time.process_time()

# 輸出結果
print("執行時間:%f 秒" % (end - start))
執行時間:0.437500 秒

除了 time.time()time.process_time() 之外,亦可考慮使用 time.perf_counter(),其用法跟 time.process_time() 都一樣,主要的差異在於 time.perf_counter() 會計算 sleep() 的時間,而 time.process_time() 不會。

import time

# 要測量的程式碼
def f():
    for i in range(10000):
        "-".join(str(n) for n in range(100))
    time.sleep(1)

start = time.process_time()
f()
end = time.process_time()
print("process_time 測量時間:%f 秒" % (end - start))

start = time.perf_counter()
f()
end = time.perf_counter()
print("perf_counter 測量時間:%f 秒" % (end - start))
process_time 測量時間:0.437150 秒
perf_counter 測量時間:1.436767 秒

timeit 模組

Python 的 timeit 是專門用來測量 Python 程式碼執行效率的模組,通常用來快速比較不同 Python 寫法的效率差異。

timeit 的使用方式很簡單,只要指定要執行的程式碼片段,並且設定重複次數:

# 引入 timeit 模組
import timeit

# 測量程式碼執行時間(重複 10000 次)
t = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

# 輸出結果
print("執行時間:%f 秒" % t)
執行時間:0.410149 秒

如果程式碼很快就執行完,就可以將重複次數設高一點,可讓測量結果比較準確。

如果要測量的程式碼比較多,也可以將要測量的程式碼寫在一個函數中,然後再用 timeit 測量該函數的執行時間:

# 引入 timeit 模組
import timeit

# 要進行測量的函數
def my_func():
    return "-".join(str(n) for n in range(100))

# 測量 my_func 執行時間(重複 10000 次)
t = timeit.timeit(my_func, number=10000)

# 輸出結果
print("執行時間:%f 秒" % t)
執行時間:0.457444 秒

如果要在一般的命列列(Windows 的命令提示字元或 Linux 的 shell)中直接使用 timeit 測量 Python 程式碼的執行時間,可以這樣用:

python -m timeit "'-'.join(str(n) for n in range(100))"
10000 loops, best of 5: 39.3 usec per loop
Windows 命令提示字元

datetime 模組

datetime 模組也可以用來測量程式的執行時間,功能跟 time.time() 相同:

# 引入 datetime 模組
import datetime

# 開始測量
start = datetime.datetime.now()

# 要測量的程式碼
for i in range(10000):
    "-".join(str(n) for n in range(100))

# 結束測量
end = datetime.datetime.now()

# 輸出結果
print("執行時間:", end - start)
執行時間: 0:00:00.435733

這種輸出格式對於長時間執行的程式很好用。

參考資料:time it Python 官方文件time Python 官方文件datetime Python 官方文件

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago