To test a program’s execution time, you measure a known code region with a monotonic clock, repeat it enough times to stabilize the result, and report a distribution rather than one number. Start by deciding whether you need wall-clock latency, CPU time, or throughput, because each answers a different question. The key condition is consistency: the same input, the same build, and the same machine state across runs. A stopwatch around main() tells you almost nothing useful if the program runs in 8 ms; a benchmark that loops 10,000 times without subtracting loop overhead can be off by more than the code it tests.

This guide covers the practical mechanics: which clock to use, how to warm up a runtime, how to separate setup from steady state, how to quantify noise, and what to report so someone else can reproduce your result. The techniques apply to compiled languages like C, C++, Rust, and Go, to managed runtimes like Java, C#, Go, and Python, and to scripts and shell commands. Examples are written in Python, C, and shell because those cover the common cases, but the reasoning transfers directly.

Decide what “execution time” means before touching a timer

There are at least four different quantities people call execution time, and they’re not interchangeable:

Wall-clock time (elapsed real time) — everything from start to finish, including waiting for I/O, scheduling delays, garbage collection, and page faults. This is what a user experiences. CPU time (user plus system) — time the processor actually spent on your process. It excludes time blocked on I/O and time the OS gave to other processes. Monotonic elapsed time inside the process — what time.perf_counter(), clock_gettime(CLOCK_MONOTONIC), and System.nanoTime() return. It advances steadily and is immune to wall-clock adjustments, but still includes scheduler preemption. Throughput and percentiles — operations per second, or the 50th, 95th, and 99th percentile latency across many requests. More informative than a mean for anything user-facing.

A microbenchmark of a sorting function wants CPU time or monotonic in-process time. A benchmark of a web endpoint wants wall-clock latency percentiles. A batch job’s cost model wants total wall time plus CPU time so you can see how much was I/O wait. Pick one primary metric and one secondary metric before you write any harness code; mixing them after the fact produces numbers nobody can compare.

Also decide the scope: the whole process (including interpreter startup and import time) or just one function or statement. Those are different measurements with different harnesses. Process-level timing is easy but dominated by startup for short programs; function-level timing needs the loops and warm-up described below.

Choose a clock and a measurement method that matches the scope

Every mainstream language ships a monotonic clock. Use it, not the system date, because the wall clock can jump backward or forward when the OS adjusts it — and a benchmark that records a negative duration is worse than useless.

Scope Python C / POSIX Java Go Shell
In-process interval time.perf_counter_ns() clock_gettime(CLOCK_MONOTONIC, …) System.nanoTime() time.Since(start) not directly available
Whole process (CPU) time.process_time() clock_gettime(CLOCK_PROCESS_CPUTIME_ID, …) ManagementFactory.getThreadMXBean() runtime metrics via profiling time -p (reports user and sys)
Whole process (wall) subprocess plus perf_counter external time external time external time time builtin

Two rules apply everywhere. First, measure the interval around exactly the code you care about, not around setup that you can hoist out of the loop. Second, use nanosecond or high-resolution timers and accumulate durations rather than repeating now() calls inside a tight inner loop — the call itself costs tens of nanoseconds and, on some platforms, more.

time.perf_counter() is monotonic and has the highest resolution Python exposes, which is why the official timeit module uses it. In C, CLOCK_MONOTONIC is the right default; CLOCK_MONOTONIC_RAW avoids NTP frequency slewing on Linux if you need maximum stability, but for most benchmarking the difference is far below your noise floor. In Java, System.nanoTime() is the documented monotonic choice; System.currentTimeMillis() is not.

Set up a fair test: inputs, build, and environment

Timing an unfair comparison wastes everyone’s afternoon. Before the first timed run:

1: Freeze the input. Generate or load input data once, outside the timed region, and reuse the same object or file. If the function consumes its input (an iterator, a stream), regenerate identical input for each iteration or include generation in a separate, reported phase. 2: Pin the build. Record compiler version, optimization flags, runtime version, and dependency lockfile. -O0 and -O2 differ by an order of magnitude on tight loops; a debug build of a managed app can be several times slower than a release build. 3: Isolate the machine as far as you can. Close other heavy processes, plug in the laptop, and note whether the CPU is thermal-throttling. On shared cloud instances, run at least three sessions at different times because noisy neighbors are real and invisible from inside your process. 4: Disable or control the things that change state mid-run. For managed runtimes, warm-up and JIT compilation are the big ones (covered next). For anything doing I/O, decide whether you’re measuring cold cache or warm cache — and say which in the report. 5: Record the environment — CPU model, core count, RAM, OS kernel, and container limits if applicable. A result without this metadata can’t be reproduced or compared.

Warm up the runtime and the code path

For interpreted and JIT-compiled languages, the first executions of a function are not representative. The interpreter may compile bytecode lazily; the JIT may start in an interpreter and only promote a method to optimized machine code after a threshold of calls; classes may load on first use; and caches (instruction cache, branch predictor, Python’s inline caches, JVM’s code cache) are cold. Java’s tiered compilation is the clearest example: a method runs interpreted or at C1 first, then at C2 once it’s “hot,” and that transition can change throughput several-fold.

The standard fix is a warm-up phase whose results you discard. A workable default is to run the measured operation 1,000–10,000 times, or for a fixed wall duration such as one to two seconds, whichever comes first, then begin recording. For very fast operations (single-digit nanoseconds), a fixed iteration count of 100,000 or more is often needed just to reach a measurable total.

Warm-up also matters for compiled languages, though for different reasons: the OS may need to fault in pages, the branch predictor and caches need to fill, and the CPU frequency governor may need to ramp up. Even in C, the first iteration of a loop over a 100 MB array is slower than the second because of page faults and cache misses. Discard the first one or two timed iterations of a long-running loop for that reason.

One caution: don’t warm up so aggressively that you exhaust caches the benchmark depends on, or so little that the JIT never engages. If in doubt, run a short pilot: time the operation 100 times, look at the per-iteration timings, and find the point where they flatten. That plateau is where measurement should start.

Work through the measurement procedure step by step

This is the core sequence, applicable whether you’re writing a harness or using an existing tool.

Prerequisite: a single function or command whose inputs you can control, plus a clock from the table above. If the program reads files or network resources, decide whether that’s part of the code under test.

1: Capture the start time immediately before the code region. Take the timestamp, then run the code, then take the end time. Store the difference. 2: Loop a known number of iterations N. For a microbenchmark, N should be large enough that total elapsed time is comfortably above timer resolution — at least a few milliseconds, ideally 50 ms to a couple of seconds. For a 20-nanosecond operation, a 100 ms target implies roughly 5 million iterations; for a 5-millisecond operation, about 20 iterations is enough to clear the noise floor. 3: Accumulate, don’t average inside the loop. Sum the durations, then divide once at the end. Integer nanosecond timers avoid floating-point drift over millions of iterations. 4: Subtract loop overhead. Measure an empty loop with the same iteration count and timing calls, then subtract its total from your result — or better, structure the loop so the overhead is a tiny fraction of the total and report it rather than subtracting. 5: Repeat the whole block several times (say 5–30 repetitions). Report each repetition, not just the mean. If the repetitions disagree by more than about 5%, something is unstable — find it before publishing numbers. 6: Compute the distribution. Minimum, median, and 95th percentile are more useful than the mean because a single scheduler hiccup can drag the mean without describing typical behavior. For tight microbenchmarks, the minimum across many repetitions is the closest estimate of the “true” cost with least interference. 7: Check success. Your result is trustworthy when the median across repetitions is stable (within a few percent between repetitions) and matches the number of iterations: total time divided by N should be consistent with the per-iteration estimate. If not, increase N, retune warm-up, or change the measurement scope.

A minimal Python harness following these rules looks like this:

That harness answers “how long does one call to sorted on this three-element list take?” The reported unit is nanoseconds per call. Note what it does not do: subtract loop overhead, control garbage collection, or isolate the CPU. Each of those is a separate refinement, and for a three-element sort they’re small relative to the signal; for a 5-nanosecond operation, they aren’t.

In C, the same shape with clock_gettime:

Two hazards here. First, the compiler may optimize work() away if its result is unused or loop-invariant; assign the result to a volatile sink or accumulate it and print it. Second, an empty loop can take a nanosecond or less per iteration at -O2, so the loop overhead is a real fraction of the measured time — measure it and state the correction.

Measure whole programs and command-line tools from outside

When you can’t instrument the code — a shell script, a third-party binary, a container image — measure from the outside. On Linux and macOS, time -p reports real, user, and system time:

The user and sys figures come from wait4 accounting and include CPU time spent by child processes, which is often what you want for a build or a data pipeline. Wall time is what you want for perceived latency. Run the command five to ten times and read the spread; the first run is usually slower because of cold disk cache, and that’s worth reporting separately rather than hiding.

For scripting languages and processes with meaningful startup cost, separate startup from execution. In Python, python -X importtime -c "import mymodule" shows import cost, which for a pandas-heavy CLI can dominate short runs. For a Node script, NODE_DEBUG or an in-process console.time around the first statement tells you whether startup is part of the problem. A short program that takes 400 ms of which 350 ms is interpreter startup has a 50 ms performance problem, not a 400 ms one — and benchmarking the process end to end will tell you the wrong story.

Containers add two wrinkles: CPU quotas can throttle you unpredictably, and multi-core machines may schedule you across cores that share a socket but not a cache. Run in the same container image and resource limits you care about, and mention them in the report.

Use existing benchmark tools instead of rebuilding them

Once you know what you’re measuring, mature harnesses save time and encode the hard-won details, especially loop-overhead accounting and statistics:

Python’s timeit handles setup hoisting, loop overhead, and repeat counts, and reports the best repeat by default. python -m timeit -s "setup" "stmt" is the fastest path for one-liners and short functions. pytest-benchmark integrates with test suites, does warm-up and calibration, and reports median and percentiles. Google Benchmark (C++) handles warm-up, CPU scaling, and statistical reporting, and it can pin threads. JMH (Java Microbenchmark Harness) is effectively mandatory for JVM microbenchmarks; it manages warm-up, JIT effects, and dead-code elimination with annotations. Criterion (Rust and Haskell via criterion) gives statistical analysis and reproducible reports. hyperfine benchmarks command-line tools with warm-up and outlier detection, and is much better than a manual shell loop.

The trade-off is that these tools encode defaults. timeit’s “best of five” can hide variance you care about; JMH’s defaults assume specific JVM behavior and need tuning for very short or very long operations. Read one level into the tool’s defaults before trusting its headline number, particularly if you will compare two versions of the code.

Understand what can distort the number, and how to detect it

Noise is not random in the way people assume; it has identifiable sources, and most of them leave a signature.

Dead-code elimination. A compiler or JIT sees that the result of a computation is unused and deletes it. The benchmark then measures nothing. Detect it by checking that removing the timing side effect slows the program down, or by feeding the result into a black-box sink. In C, volatile or inline assembly barriers are common; in Java, returning the value from the benchmark method and consuming it in JMH’s Blackhole.

Constant folding and hoisting. If the input is a compile-time constant, the compiler may compute the answer at build time. Feed inputs from a runtime source (command line, file, or a volatile variable) when this is a risk.

CPU frequency scaling and turbo. A short burst can run above the sustained clock, so a microbenchmark reports better throughput than the same code in a long-running workload. Conversely, thermal throttling makes later repetitions slower. If the spread between the fastest and slowest repetition is large, suspect frequency behavior or another process on the machine.

Scheduler preemption. A single long measured run can contain a context switch that adds milliseconds. Many short repetitions make this visible as a tail; report the median or minimum alongside the mean, and don’t present the mean as typical.

Memory effects. Working-set size determines whether you measure cache or DRAM. A benchmark on a 2 KB array is a cache benchmark; a benchmark on a 200 MB array is a memory-bandwidth benchmark. State your working-set size, because results don’t transfer between the two.

Garbage collection. In managed runtimes, allocation inside the timed region triggers collections whose cost depends on heap size and GC configuration. Either measure with allocation outside the loop, or report the GC configuration and include allocation, because production code does allocate.

Timer granularity and cost. Some platforms’ timers have resolutions of tens of nanoseconds or worse, and the call itself costs time. For operations near that scale, time batches and divide rather than timing individual operations.

A simple detection routine catches most of these: run the same benchmark several times in a session, and once more in a fresh session. If the within-session repetitions agree but the across-session numbers differ, the environment changed. If the repetitions disagree, something in the timed region is nondeterministic — find it rather than averaging it away.

Report results so someone else can reproduce them

A number without context is an anecdote. A useful report includes:

The metric and its unit (for example, median nanoseconds per call, plus p95). The exact code region measured, including whether setup and I/O were inside it. Iteration counts, warm-up counts, and number of repetitions, plus how the reported statistic was chosen. Language, compiler or runtime version, optimization flags, and libraries. Hardware: CPU model, core count, memory, OS version, container limits. Input sizes and working-set sizes. Any corrections applied (loop overhead, dead-code sink) and any known noise sources. The raw repetition timings, not just the summary — it costs one line and lets a reader judge stability.

For comparisons between two versions, use the same harness and environment for both, alternate them (A, B, A, B) to cancel drift, and state the observed difference in the same units. A change from 1.02 ms to 0.98 ms is 40 microseconds, or about 4% — and if the between-repetition spread is ±5%, that difference isn’t established by this data. Saying so is more useful than a bold percentage.

Finally, match the measurement to the decision. If you’re choosing between two algorithms, benchmark at realistic input sizes and at the sizes near where the crossover might occur. If you’re verifying a fix, benchmark the failing case and the typical case. If you’re publishing, publish the harness alongside the numbers. The execution time of a program is not a single fact; it’s a property of code, input, environment, and measurement method together, and a good test reports all four.