CODE/2022-09-20

Five Ways to Measure Python Execution Time

Measuring execution time helps identify slow operations and compare implementations. Choose the measurement method according to whether you need a single elapsed duration, a repeated benchmark, or reusable instrumentation.

1. Wall-clock time

python_snippet
Python · 5 lines|
import time
start = time.time()
time.sleep(0.1)
print(f"Elapsed: {time.time() - start:.4f}s")
time.time() is a wall clock and may change if the system clock is adjusted. For durations, prefer a monotonic performance counter.

2. Performance counter

python_snippet
Python · 5 lines|
import time
start = time.perf_counter()
time.sleep(0.1)
print(f"Elapsed: {time.perf_counter() - start:.4f}s")
The elapsed duration includes sleep and I/O waits. Only the difference between readings is meaningful.

3. Repeat with timeit

python_snippet
Python · 7 lines|
import timeit
def work():
return sum(range(100))
seconds = timeit.timeit(work, number=1000)
print(f"Total for 1000 calls: {seconds:.6f}s")
timeit uses a performance counter by default. Repeat measurements when benchmarking short operations, and remember that a benchmark can be affected by its environment.

4. Use a decorator

python_snippet
Python · 18 lines|
from functools import wraps
from time import perf_counter
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__}: {perf_counter() - start:.6f}s")
return wrapper
@timed
def work():
return sum(range(1000))
work()
This wrapper is for synchronous functions. To time an async function, await it inside an async wrapper:
python_snippet
Python · 20 lines|
import asyncio
from functools import wraps
from time import perf_counter
def timed_async(func):
@wraps(func)
async def wrapper(*args, **kwargs):
start = perf_counter()
try:
return await func(*args, **kwargs)
finally:
print(f"{func.__name__}: {perf_counter() - start:.6f}s")
return wrapper
@timed_async
async def fetch():
await asyncio.sleep(0.1)
return "done"
asyncio.run(fetch())
The elapsed time includes time spent awaiting. The finally block also reports the duration if the coroutine raises or is cancelled.

5. Time a block with a context manager

python_snippet
Python · 13 lines|
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer(label):
start = perf_counter()
try:
yield
finally:
print(f"{label}: {perf_counter() - start:.6f}s")
with timer("work"):
sum(range(1000))
The finally block records time even if the operation raises; it does not suppress the exception.
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·