57

I want to find out for how long (approximately) some block of code executes. Something like this:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);

How?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
snakile
  • 52,936
  • 62
  • 169
  • 241

8 Answers8

87

You can use the clock method in time.h

Example:

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
Joey
  • 344,408
  • 85
  • 689
  • 683
KLee1
  • 6,080
  • 4
  • 30
  • 41
  • +1: Nice and simple. However, won't you need to cast `(end - start)` to a floating point before the division if you want to get fractions of a second? – torak Aug 24 '10 at 14:25
  • @torak Yes, I think you're right, I haven't had a chance to test it though. – KLee1 Aug 24 '10 at 14:53
  • 20
    Note that `clock()` measures CPU time, not wall-clock time (this may or may not be what you want). – caf Aug 25 '10 at 03:09
  • 4
    @caf While true on Linux, clock() actually computes wall-clock time on Windows: http://msdn.microsoft.com/en-us/library/4e2ess30.aspx – undefined Sep 26 '14 at 23:56
  • 1
    @undefined: Not just Linux, it's actually the C standard that says *"The `clock` function determines the processor time used."*. I suppose on Windows you can simply say that the implementation's best approximation to processor time used is wall-clock time used. – caf Oct 01 '14 at 13:12
  • 2
    Note : For anybody confused CLOCKS_PER_SEC is NOT your cpu's clock frequency. – tur1ng Nov 27 '17 at 20:50
  • what the heck is a "CLOCKS_PER_SEC". this is not the right answer – WhyWhat Oct 15 '22 at 09:24
26

You can use the time.h library, specifically the time and difftime functions:

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );

  return 0;
}

(Example adapted from the difftime webpage linked above.)

Please note that this method can only give seconds worth of accuracy - time_t records the seconds since the UNIX epoch (Jan 1st, 1970).

Stephen
  • 6,027
  • 4
  • 37
  • 55
  • 1
    This gives only seconds precision. And your example actually doesn't use the ``. – Dummy00001 Aug 24 '10 at 15:15
  • Sorry, the 'c' was a typo - the ctime library is defined in `time.h`. And yes, it gives only seconds accuracy. Considering the poster said "approximately", I considered that enough. I will edit my answer to include the fact that it will only give seconds level of accuracy, if you wish. – Stephen Aug 24 '10 at 15:24
6

Sometime it's needed to measure astronomical time rather than CPU time (especially this applicable on Linux):

#include <time.h>

double what_time_is_it()
{
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    return now.tv_sec + now.tv_nsec*1e-9;
}

int main() {
    double time = what_time_is_it();
    printf("time taken %.6lf\n", what_time_is_it() - time);
    return 0;
}
Ivan Talalaev
  • 6,014
  • 9
  • 40
  • 49
  • It gives much better precision than clock()! But it is worth to mention that just including time.h was not sufficient for me. I had to link the executable with `-lrt`. – Alexander Samoylov May 01 '23 at 12:44
4

The standard C library provides the time function and it is useful if you only need to compare seconds. If you need millisecond precision, though, the most portable way is to call timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep. This is a useful property for benchmarking and implementing delays that take running time into account.

Daniel
  • 556
  • 3
  • 5
3

GetTickCount().

#include <windows.h>
void MeasureIt()
{
    DWORD dwStartTime = GetTickCount();
    DWORD dwElapsed;

    DoSomethingThatYouWantToTime();

    dwElapsed = GetTickCount() - dwStartTime;

    printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
}
selbie
  • 100,020
  • 15
  • 103
  • 173
2

For sake of completeness, there is more precise clock counter than GetTickCount() or clock() which gives you only 32-bit result that can overflow relatively quickly. It's QueryPerformanceCounter(). QueryPerformanceFrequency() gets clock frequency which is a divisor for two counters difference. Something like CLOCKS_PER_SEC in <time.h>.

#include <stdio.h>
#include <windows.h>

int main()
    {
    LARGE_INTEGER tu_freq, tu_start, tu_end;
    __int64 t_ns;

    QueryPerformanceFrequency(&tu_freq);
    QueryPerformanceCounter(&tu_start);
    /* do your stuff */
    QueryPerformanceCounter(&tu_end);

    t_ns = 1000000000ULL * (tu_end.QuadPart - tu_start.QuadPart) / tu_freq.QuadPart;
    printf("dt = %g[s]; (%llu)[ns]\n", t_ns/(double)1e+9, t_ns);

    return 0;
    }
tansy
  • 486
  • 3
  • 8
1

I would use the QueryPerformanceCounter and QueryPerformanceFrequency functions of the Windows API. Call the former before and after the block and subtract (current − old) to get the number of "ticks" between the instances. Divide this by the value obtained by the latter function to get the duration in seconds.

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
0

If you don't need fantastic resolution, you could use GetTickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx (If it's for something other than your own simple diagnostics, then note that this number can wrap around, so you'll need to handle that with a little arithmetic).

QueryPerformanceCounter is another reasonable option. (It's also described on MSDN)

user357501
  • 11
  • 1