is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.
Thanks
is there any simple way how to measure computing time in C? I tried time utility when executed, but I need to measure specific part of a program.
Thanks
You can use the clock
function in <time.h>
along with the macro CLOCKS_PER_SEC
:
clock_t start = clock() ;
do_some_work() ;
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
Now elapsed_time
holds the time it took to call do_some_work
, in fractional seconds.
You can try the profiler "gprof". More information here: http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html
You can generally use the clock()
function to get the start and end times of a single call to your function being tested. If, however, do_some_work()
is particularly fast, it needs to be put in a loop and have the cost of the loop itself factored out, something like:
#define COUNT 10000
// Get cost of naked loop.
clock_t start_base = clock();
for (int i = count; i > 0; i--)
;
clock_t end_base = clock();
// Get cost of loop plus work.
clock_t start = clock();
for (int i = count; i > 0; i--)
do_some_work() ;
clock_t end = clock();
// Calculate cost of single call.
double elapsed_time = end - start - (end_base - start_base);
elapsed_time = elapsed_time / CLOCKS_PER_SEC / COUNT;
This has at least two advantages:
clock()
function has a limited resolution.@codebolt - Thank you! very nice. On Mac OS X, I added an include of time.h, and pasted in your four lines. Then I printed the values of start, stop (integers) and elapsed time. 1mS resolution.
output:
3 X: strcpy .name, .numDocks: start 0x5dc end 0x5e1 elapsed: 0.000005
calloc: start 0x622 end 0x630 elapsed: 0.000014
in my foo.c program I have
#include <libc.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
but it works without explicitly including time.h. One of the others must bring it in.
Actual code:
clock_t start = clock() ;
strcpy( yard2.name, temp ); /* temp is only persistant in main... */
strcpy( yard1.name, "Yard 1");
strcpy( yard3.name, "3 y 3 a 3 r 3 d 3");
yard1.numDocks = MAX_DOCKS; /* or so I guess.. */
yard2.numDocks = MAX_DOCKS; /* or so I guess.. */
yard3.numDocks = MAX_DOCKS; /* or so I guess.. */
clock_t end = clock() ;
double elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
printf("3 X: strcpy .name, .numDocks: start 0x%x end 0x%x elapsed: %-12:8f \n", start, end, elapsed_time );
start = clock() ;
arrayD = calloc( yard2.numDocks, sizeof( struct dock ) ); /* get some memory, init it to 0 */
end = clock() ;
elapsed_time = (end-start)/(double)CLOCKS_PER_SEC ;
printf("calloc: start 0x%x end 0x%x elapsed: %-12:8f \n", start, end, elapsed_time );