Jump to content

timeslice.h

From Hugo's wiki

timeslice.h is a public domain wall-clock timer for C99 (and C++) that measures time intervals accurately.

The whole library is static inline: there is no implementation file and no call overhead. A measurement costs only the clock reads themselves (~20–30 ns on Linux, where clock_gettime(CLOCK_MONOTONIC) is served from the vDSO without a syscall).

Usage

#include "timeslice.h"

Time_Slice t0, t1;

get_time_slice(&t0);
// ... code to measure ...
get_time_slice(&t1);

double ns  = calc_time_diff(t0, t1, TIME_NS);
double us  = calc_time_diff(t0, t1, TIME_US);
double ms  = calc_time_diff(t0, t1, TIME_MS);
double sec = calc_time_diff(t0, t1, TIME_SEC);
  • get_time_slice reads CLOCK_MONOTONIC twice, back to back, and stores both raw values. It returns 0, or -1 on failure.
  • calc_time_diff returns the elapsed time in the requested unit, or -1.0 for invalid input.

CLOCK_MONOTONIC is unaffected by NTP or manual date changes, so it never jumps backwards.

Overhead correction

The interval is measured from the last clock read of the first call to the first read of the second call. That leaves out the two internal gaps between the reads of each call, and the first call's prologue and second call's epilogue fall outside by construction.

What remains is the code plus a few nanoseconds of call tail. The two internal gaps are samples of that same per-read cost, taken by the same calls under the same cache and scheduler conditions. So calc_time_diff subtracts their average: it calibrates itself, with no separate calibration pass. The result is clamped at 0 for code faster than the overhead estimate.

See also