Precise timing with clock_gettime()
What you'll learn: How to use the Linux-standard clock_gettime() function to measure code execution speed with nanosecond precision.
Why precision matters
When you want to see how fast a piece of code runs, you might be tempted to look at a wall clock or use basic functions like time(). However, standard seconds are like trying to measure a grain of sand with a yardstick—the scale is just too large. Most modern C functions execute in microseconds or even nanoseconds. To catch these "speed demons," we need a high-resolution timer.
Meet clock_gettime()
In the POSIX environment (Linux/Unix), the gold standard for profiling is clock_gettime(). It doesn't just return an integer; it fills a special structure called timespec that tracks two things: seconds and nanoseconds.
Think of it like a stopwatch that records the hour and the tiny ticks of a hummingbird's wings simultaneously.
How to use it
To measure a block of code, you take a "snapshot" of the time right before the code starts and another right after it finishes. By subtracting the start time from the end time, you get the elapsed duration.
#include <stdio.h>
#include <time.h>
int main() {
struct timespec start, end;
// 1. Capture the start time
clock_gettime(CLOCK_MONOTONIC, &start);
// 2. The code you want to profile
for (int i = 0; i < 1000000; i++);
// 3. Capture the end time
clock_gettime(CLOCK_MONOTONIC, &end);
// 4. Calculate the difference in seconds
double time_taken = (end.tv_sec - start.tv_sec) +
(end.tv_nsec - start.tv_nsec) / 1e9;
printf("Code took %f seconds to execute\n", time_taken);
return 0;
}
The "Monotonic" Secret
Notice the CLOCK_MONOTONIC constant in the code. Unlike CLOCK_REALTIME (which tracks the actual time of day), a monotonic clock is a simple counter that never goes backward. If the system clock updates via the internet while your program is running, a "real-time" clock might jump, ruining your measurement. A monotonic clock is a steady, reliable heartbeat perfect for profiling.
Key takeaway
Use clock_gettime() with CLOCK_MONOTONIC to capture execution times down to the nanosecond for accurate performance profiling.