Structured, zero-dependency Python timing for humans and telemetry.
Instantly isolate wall-clock latency from CPU burn across sync, async, and generators.
Why TimeRun?
When your service or script is slow, is it waiting on network I/O or burning CPU?
Standard time.perf_counter() forces you to write repetitive boilerplate, manual float subtractions, and separate calls to time.thread_time(). Heavy profilers (cProfile, py-spy) and APM agents (Datadog, New Relic) introduce massive overhead, binary dependencies, or vendor lock-in.
TimeRun bridges the gap: a single-file, zero-dependency library providing nanosecond-precision wall and CPU timing, bounded execution history, and plug-and-play callbacks for your observability stack.
-
ðŠķ Zero Dependencies
Standard library only. Safe for libraries, microservices, and air-gapped environments. Single-file architecture with 100% test coverage.
-
âąïļ Wall + CPU Isolation
Separates elapsed clock time (
perf_counter_ns) from compute time (thread_time_ns). Instantly diagnose whether latency is I/O or CPU bound. -
ð Observability Ready
Export directly to OpenTelemetry spans, Prometheus histograms, Datadog, or JSON loggers with one lightweight
on_endcallback. -
⥠Async & Thread Safe
Native support for
async with, async functions, sync/async generators, and multi-threading with task-isolatedContextVarstacks.
Installation
Install TimeRun from PyPI. Requires Python 3.10+.
Quickstart
1. Measure Code Blocks (Wall vs. CPU)
Wrap any block in with Timer() as m: (or async with Timer() as m:). On exit, m.wall_time and m.cpu_time are immediately available:
import time
from timerun import Timer
with Timer() as m:
time.sleep(0.05) # Simulates network I/O or database wait
total = sum(i * i for i in range(100_000)) # Simulates CPU computation
print("Elapsed (Wall):", m.wall_time.timedelta) # e.g., 0:00:00.055120
print("Compute (CPU): ", m.cpu_time.timedelta) # e.g., 0:00:00.005110
Why measure both wall-clock and CPU time?
If wall time is 2 seconds but CPU time is 5 milliseconds, your code spent 99.7% of its time waiting on I/O. If both are 2 seconds, you have a CPU bottleneck.
2. Time Functions and Generators
Use @Timer() on sync or async functions. The wrapped function retains a bounded deque of measurements:
from timerun import Timer
@Timer(maxlen=100)
def process_batch(items):
return [x * 2 for x in items]
process_batch([1, 2, 3])
last = process_batch.measurements[-1]
print("Wall time:", last.wall_time.timedelta)
print("CPU time: ", last.cpu_time.timedelta)
3. Stream to Logs & Observability
Use on_end to ship timings directly to your logs, OpenTelemetry, Prometheus, or Datadog without adding vendor dependencies to your core logic:
import logging
from timerun import Timer
logger = logging.getLogger("app")
def log_timing(m):
logger.info(
"task_finished",
extra={
"wall_s": m.wall_time.duration / 1e9,
"cpu_s": m.cpu_time.duration / 1e9,
**m.metadata,
},
)
with Timer(metadata={"endpoint": "/checkout"}, on_end=log_timing):
pass # your business logic
How It Compares
| Feature | Manual time.perf_counter() |
Heavy Profilers (cProfile, py-spy) |
APM Agents (Datadog, New Relic) |
TimeRun |
|---|---|---|---|---|
| Dependencies | None | Extra tooling | Large binary agents | Zero (stdlib only) |
| Wall vs. CPU Breakdown | â Manual boilerplate | â ïļ Sampling overhead | â Usually wall only | â Built-in & precise |
| Structured Output | â Raw floats | â Binary trace files | â ïļ Proprietary format | â
Structured Measurement |
| Asyncio & Thread Safe | â Race condition risk | â ïļ Global runtime cost | â Handled by agent | â Task & Thread isolated |
| Telemetry Integration | â Build it yourself | â Offline analysis only | â ïļ Vendor locked | â
Agnostic (on_end) |
| Footprint | 0 LOC | Heavy | Large background daemon | Single file (~500 LOC) |
Explore the Docs
-
ð API Guide
Detailed concepts and lifecycle for
Timer,Measurement, andTimeSpan, including concurrency and callbacks. -
ðē Cookbook & Recipes
Production recipes for FastAPI, OpenTelemetry, Structlog, LLM token streaming, and statistical analysis.