Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

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().

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top