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 returns time as a data-structure (struct timespec) that includes the current time in seconds and nano-seconds. Call this 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.

 

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

{

}

void testThis()

{

int i;

struct timespec start, end, diff;

 

clock_gettime(0, &start);

for (i = 0; i < 100000; i++)

{

x = i * 45;

}

clock_gettime(0, &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 *