C — How to check how much time a section of code takes to execute.

This requires use of standard C library support for the clock_gettime() function. This function returns clock time as a data-structure (struct timespec) that includes the the clock time in seconds and nano-seconds.

Call this function one time before the section of code to evaluate and once after and then take a difference of the end time versus the start time to figure out the time taken in the section of code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <time.h> // for the clock_* APIs and struct timespec

struct timespec timespec_diff(struct timespec end, struct timespec start)

{
    timespec temp;


    if ((end.tv_nsec-start.tv_nsec) < 0)
    { // If this is the case, then the seconds values are different by atleast 1.
        temp.tv_sec = end.tv_sec - start.tv_sec - 1; // Borrow one second from the seconds field...
        temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; //...and use it in the nano-second field.
    }
    else
    {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }

    return temp;
}

void testThis()
{
    int i;
    struct timespec start, end, diff;


    clock_gettime(CLOCK_REALTIME, &start);

    for (i = 0; i < 100000; i++)
    {
        x = i * 45;
    }

    clock_gettime(CLOCK_REALTIME, &end);

    diff = timespec_diff(end, start);
    printf("Section of code took %u seconds %d nano-seconds\n", diff.tv_sec, diff.tv_nsec);
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *