C - measuring computing time

10,962

Solution 1

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.

Solution 2

You can try the profiler "gprof". More information here: http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html

Solution 3

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:

  • you'll get an average time which is more representative of the actual time it should take; and
  • you'll get a more accurate answer in the case where the clock() function has a limited resolution.
Share:
10,962

Related videos on Youtube

Waypoint
Author by

Waypoint

Updated on June 04, 2022

Comments

  • Waypoint
    Waypoint almost 2 years

    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

  • Jonathan Leffler
    Jonathan Leffler about 13 years
    The only problem here is that CLOCKS_PER_SEC, but the value is typically 60 or 100, so the timing is not very precise. You can do quite a lot in 10 or 17 ms if your processor has multiple cores and runs at 3 GHz.
  • Rune Aamodt
    Rune Aamodt about 13 years
    That's true, but I'm pretty sure this is the best you can get with pure ANSI C. On Windows, you can use timeGetTime or even QueryPerformanceCounter to do better.
  • wallyk
    wallyk about 13 years
    If do_some_work() is very quick, it might be necessary to put it inside a loop which repeats it many times, like 10,000,000 and divide the elapsed time by the same number to calculate the time for one unit of work.
  • Mike Dunlavey
    Mike Dunlavey about 13 years
    He can try it, but he might not like it. See here.
  • BiGYaN
    BiGYaN about 13 years
    @Mike, I never knew about the recursion issues. Thanks for pointing this out.

Related