Master the fundamental concepts of profiling & measurement through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksclock_gettime(CLOCK_MONOTONIC) is what glibc, LLVM's benchmark harness, and the Linux kernel's own microbenchmarks use for sub-millisecond timing. Unlike gettimeofday, monotonic clocks never jump backward when NTP adjusts wall time. Pairing start and end reads around a tight loop is the foundation of every custom benchmark harness.
Read timespec at region start and end, subtract, convert to nanoseconds or microseconds. Warm up caches before the timed region so cold-start effects do not dominate.
cLoading…
CLOCK_PROCESS_CPUTIME_ID measures CPU time, not sleep timeKeep the relevant documentation open while you implement. When your output disagrees with the reference, trace one failing case by hand before changing random lines.
You will implement now_ns() and wrap a benchmark region with warmup plus repeated samples. This exercise asks you to report elapsed time for a known workload and verify results are stable across runs.
A home-made timer built on clock_gettime has three classic bugs. The first is getting the timespec subtraction wrong when the nanosecond field wraps (you must borrow a second). The second is using CLOCK_REALTIME, which can jump backwards when NTP adjusts the clock. The third is timing something so short that the overhead of reading the clock dominates. Given recorded timespec pairs, compute intervals correctly, detect those problems, and derive per-operation costs.
cLoading…
tv_sec >= 0 and 0 <= tv_nsec <= 999999999, otherwise print NAME: invalid timespec (tv_nsec must be 0..999999999).sec = S2 - S1, nsec = NS2 - NS1; if nsec < 0, borrow one second (sec--, nsec += 1000000000).clock went backwards by X (wall-clock adjustment: use CLOCK_MONOTONIC);end is before start (a monotonic clock never goes back: check the order).N ns below 1 µs, N.NNN us below 1 ms, N.NNN ms below 1 s, and N.NNNNNNNNN s otherwise (truncated).clock: monotonic or realtime, calibrate: need back-to-back deltas, per NAME: no such interval, and per NAME: need at least 1 operation.cLoading…
Input:
cLoading…
Output:
cLoading…
double, because a double cannot hold nanoseconds since the epoch exactly.Hidden tests cover borrows at exact second boundaries, a long interval of hours, intervals before and after calibration, a zero-length interval, per-operation costs below one nanosecond, and invalid input.