views:

760

answers:

4

I need to measure, in C++ on Linux (and other Unix-like systems), the CPU (not wall clock) time taken by a long computation, so I'm using clock(). Problem: on 32 bit systems, this wraps around after about 2000 or 4000 seconds.

What's the recommended workaround for this?

+1  A: 

Do you need the precision provided by clock()? If not, you can use time() twice and take the difference:

time_t start, end;
double diff;

time(&start);
// Do your stuff...
time(&end);
diff = difftime(end, start);

EDIT: time() measures the real time (not CPU time) as litb pointed out in his comment, but so does clock(). If you want to measure CPU time, you should follow litb's advice and use getrusage().

Can Berk Güder
isn't time measuring wall-clock-time? i.e it won't be less if your program uses less cpu. it's measuring real seconds from 1970.
Johannes Schaub - litb
that's correct, but so does clock()
Can Berk Güder
well as no-one seem to correct you, i'll do again: clock is not wall-clock time. it returns "an approximation of processor time used by the program".
Johannes Schaub - litb
I didn't know that. Any reference you might point to?
Can Berk Güder
A: 

Get the time on a recurring basis and also increment a multiplier variable int every time it rolls over?

Dave Swersky
+12  A: 

You want to use getrusage which fills the following struct:

struct rusage {
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    ...
};

For completion, struct timeval:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

As always, consult the manpage for details (man getrusage)

Johannes Schaub - litb
+1  A: 

Another possible method is to use gettimeofday() twice as it returns ms accuracy.

James Fisher