Measure time execution in a C program

There are many ways to measure time in a C program. I use clock_gettime() since it supports high resolution clock which we can count on.

Header
#include <time.h>

Time storage structure
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

Function
int clock_gettime(clockid_t clk_id, struct timespec *tp);
is used to retrieve the time of the specified clock clk_id.

There are several kind of clock ID but the two of them may be used the most.
CLOCK_REALTIME: System-wide clock that measures real (i.e., wall-clock) time.
CLOCK_MONOTONIC: Clock that cannot be set and represents monotonic time since some unspecified starting point. On Linux, that point corresponds to the number of seconds that the system has been running since it was booted.

Below is an example of using the function.

#include <stdio.h>
#include <time.h>

struct timespec time_subtract(struct timespec t1, struct timespec t2)
{
    struct timespec dur;
    if (t1.tv_nsec > t2.tv_nsec)
    {
        dur.tv_sec = t2.tv_sec - t1.tv_sec - 1;
        dur.tv_nsec = 1000000000 + t2.tv_nsec - t1.tv_nsec;
    }
    else
    {
        dur.tv_sec = t2.tv_sec - t1.tv_sec;
        dur.tv_nsec = t2.tv_nsec - t1.tv_nsec;
    }
    return dur;
}

int main()
{
    struct timespec t1, t2, dur;
    clock_gettime(CLOCK_MONOTONIC, &t1);

    // The tasks that we want time measurement here...

    clock_gettime(CLOCK_MONOTONIC, &t2);
    dur = time_subtract(t1, t2);
    printf("Task Execute Time: %lu.%09lu\n", dur.tv_sec, dur.tv_nsec);
    return 0;
}

Note: don't for get the struct keyword for timespec otherwise there will be an error if you compile for C
Note 2: be careful when do subtraction on 2 time_t variables. See this post

Comments