c programming tips and tricks

Calculate Elapsed Time

Friends, have you ever needed to calculate the time passed between two events? Or keep a check on some function which is spuriously taking extra execution time than expected?

Here is the code snippet implemented using a set of macros to help you figure out how long something will take to run.

#include "stdafx.h"
#include <time.h>
#include <windows.h>
#include <stdlib.h>
clock_t startm, stopm;
#define BEGIN if ( (startm = clock()) == -1) \
{ \
printf("clock returned error.");exit(1); \
} \
#define CLOSE if ( (stopm = clock()) == -1) \
{printf("clock returned error."); \
exit(1); \
} \
#define SHOWTIME printf( "%6.3f seconds elapsed.", ((double)stopm-startm)/CLOCKS_PER_SEC);
main() {
     // Specify set of instructions for you want to measure execution time

Leave a Reply

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