samiuljahan's blog

there's always room for improvement

How to calculate the time required for a block of code in C/C++?

leave a comment »

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

Written by সামিউল(samiul)

September 10, 2011 at 6:18 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.