How to calculate the time required for a block of code in C/C++?
Here are a small code snippets with which you can calculate the execution time of a certain block of codes in C/C++.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);
int main() {
START;//start the timer
//code blocks which execution time will be counted begins here
int n;
for(n = 0; n<=65535; n++)
{
printf("%d\n", n);
}
//code blocks which execution time will be counted ends here
STOP;//end the timer
PRINTTIME;//print the time
return 0;
}
The program will print total 65536 numbers line by line and at the end it’ll print the total seconds e.g 5.109 seconds, it took to print the numbers
—–courtesy: http://kennethfinnegan.blogspot.com/2008/03/timing-events-in-c.html
Advertisement

