CODE/2022-09-20

Measuring Execution Time in Python

A Python program can spend time executing on the CPU, waiting for I/O, or sleeping. Choose a clock that measures the quantity you actually need.

Measure elapsed time

For the duration of an operation, use time.perf_counter() and subtract two readings:
python_snippet
Python · 6 lines|
import time
start = time.perf_counter()
time.sleep(1) # Replace with the operation being measured.
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.3f} seconds")
Elapsed time includes sleep and waiting. Only differences between readings are meaningful.

Measure process CPU time

python_snippet
Python · 5 lines|
import time
start = time.process_time()
result = sum(range(1_000_000))
print(f"CPU time: {time.process_time() - start:.6f} seconds")
process_time() measures CPU time used by the current process and excludes sleep. It is not necessarily equal to elapsed time; multi-threaded CPU usage can also accumulate across threads.

Wall-clock timestamps

time.time() returns seconds since the Unix epoch, and datetime.now() gives a calendar timestamp. They are useful for timestamps but system clock adjustments can affect duration measurements. When subtracting datetime values, use delta.total_seconds() rather than delta.seconds, which excludes whole days.
The old time.clock() API was platform-dependent and was removed in Python 3.8. Use perf_counter() for elapsed duration or process_time() for process CPU time.
COMPANION ESSAYS / 思想脉络与互照篇目
同卷深读2026-05-22 ·

Installing Python 3 Alongside System Python on CentOS 7

同属「系统工程卷」脉络衍生思考与工程推演推演阅读 →
跨界互照2026-08-22 ·

我的书架:03|金融经管:经济运行、金融体系与企业治理

我的书架:03|金融经管:经济运行、金融体系与企业治理

跨领域对照思辨 · 从「思想随笔」视界互为印证推演阅读 →
RELATED INDEX / 相关阅读索引
柯航hang.ke·© 2014—2026
CC BY-NC 4.0·