The need:
Need is same as previous program which gives you precision of nanoseconds but that program would work only on linux. This program will work on windows also but will give you precision of milli seconds only. All you need to do is to place your test program code (the code whose execution time is to be measured) in between the comments which indicate the start and end of the program.
The code:
----------------------------------------------------------
/*This program should work on both windows and linux*/ #include<time.h> #include<stdio.h> #include<stdlib.h> #define START if ( (start_time = clock()) == -1) {printf("Could not call clock");exit(1);} #define STOP if ( (stop_time = clock()) == -1) {printf("Could call clock");exit(1);} #define PRINT_TIME_DIFF printf( "Your program took %.3f seconds.\n", ((double)stop_time-start_time)/CLOCKS_PER_SEC); int main() { clock_t start_time, stop_time; int i=0; START //test program code begins //test program code ends STOP PRINT_TIME_DIFF return 0; }
----------------------------------------------------------
Approach:The approach is simple. There is a built-in function clock() in <time.h> header file. In this program I have use macros to differentiate between your test code and the statement which would be used to print the time and other things. I thought this would simplify the look of the program a little bit.
Remarks:
1. This program should work on both windows and linux.
2. This program will give accuracy of (1/1000)th part of a second.
Showing error with the use of STOP.
ReplyDeleteThere is no error with the program. I double checked it.
ReplyDeleteWhat is the error you are getting and which compiler are you using? Please specify.