Medium
Measuring an interval with CLOCK_REALTIME
This benchmarking helper times an operation using CLOCK_REALTIME. It runs correctly in isolated testing, but in production the printed duration is occasionally a large negative number. What's wrong, and what's the correct fix?
bench.cpp
#include <time.h>
#include <cstdio>
long long now_ns() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return (long long)ts.tv_sec * 1'000'000'000LL + ts.tv_nsec;
}
void time_operation() {
long long start = now_ns();
do_work();
long long end = now_ns();
printf("elapsed: %lld ns\n", end - start); // occasionally negative in production
}40 of 53 in Operating Systems