In C, there are too many ways to time a piece of code. As I always have no idea what is good for what, I wrote this snippet based on clock_gettime. The MONOTONIC clock guarantees the clock will never run backward, and the function itself is much faster than a system call. I believe this is a good default choice for most cases.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <time.h>

double elapsed(struct timespec *start, struct timespec *end) {
    return (end->tv_sec - start->tv_sec) + 1e-9 * (end->tv_nsec - start->tv_nsec);
}

int main() {
    struct timespec start, end;
    clock_gettime(CLOCK_MONOTONIC, &start);

    /* some computation */

    clock_gettime(CLOCK_MONOTONIC, &end);
    printf("%.3lf seconds\n", elapsed(&start, &end));
    return 0;
}