rwallace
rwallace

Reputation: 33445

32 bit Linux clock() overflow

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?

Upvotes: 2

Views: 2038

Answers (4)

James Fisher
James Fisher

Reputation: 292

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

Upvotes: 1

Can Berk Güder
Can Berk Güder

Reputation: 113350

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

Upvotes: 1

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507085

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)

Upvotes: 12

Dave Swersky
Dave Swersky

Reputation: 34810

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

Upvotes: -1

Related Questions