brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's time.perf_counter is the clock for timing a piece of your code

Python
~/tips/tip-python-time-perf-counter

import time

Measure how long a block of code takes with the right clock.

To see how long one step inside a bigger script takes, I’d wrap it with time.perf_counter(). It’s built for exactly that.

import time

start = time.perf_counter()
rows = load_rows("export.csv")
print(f"load took {time.perf_counter() - start:.3f}s")

It’s the clock with the highest available resolution, and it only moves forward. time.time() is the wall clock, so it can jump when NTP corrects the system time or you change it by hand, and a measurement across that jump is nonsense, even negative.

The value itself means nothing. It’s counted from an undefined starting point, so only the difference between two calls is useful. Don’t store it as a timestamp.

If you want CPU time instead of elapsed time, time.process_time() leaves out the time your program spent waiting on disk, network or sleep. Comparing the two tells you whether a slow step is busy or just waiting.

For a tiny snippet that runs in microseconds, one measurement is mostly noise. That’s where timeit is better, since it repeats the code many times. I’d use perf_counter for real steps in a real script, like a download or a database query.

Further reading: time.perf_counter

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link