Reputation: 193
How can i record the running time of my program every time I insert an input?I tried this particular method:
clock_t tStart = clock(),tEnd;
And after printing the ouput:
tEnd = clock();
printf("Time taken: %.6fs\n", (double)(tEnd - tStart) / CLOCKS_PER_SEC);
However,I sometimes end up having just a bunch of 0s when calculating the miliseconds.Is there any method to improve this?
Upvotes: 0
Views: 297
Reputation: 51934
Perhaps try a higher resolution timer which may be available on your platform:
Linux: clock_gettime(CLOCK_REALTIME, &timeSpec)
Windows: QueryPerformanceCounter(&performanceCount)
Upvotes: 3
Reputation: 44250
In unix,usetime
, which forks&execs the program, and does a get_rusage()
after the child exited.
So, you don't have to instrument the program itself.
plasser@pisbak:$ time ./a.out omg.dat
real 0m10.276s
user 0m9.986s
sys 0m0.291s
plasser@pisbak:$
Upvotes: 1
Reputation: 125037
Is there any method to improve this?
If you don't have a better timer, as suggested in jspcal's answer, then another solution is to repeat the same operation a large number of times and then divide the elapsed time by the number of repetitions:
const int REPS = 10000;
clock_t tStart = clock(),tEnd;
for (int i = 0; i < REPS; i++) {
// do your work here
}
tEnd = clock();
double time = (double)(tEnd - tStart)/REPS;
printf("Time taken: %.6fs\n", time / CLOCKS_PER_SEC);
Upvotes: 3