Measuring running time in a general + portable way

W

websnarf

I'm trying to find a decent way of measuring the running time of a
long-running program.
Say, the running time ranges from several seconds to more than a day.

The standard clock() function seems inadequate for this task.
(I read somewhere in this group that clock_t would likely overflow
after <1 hour).

Is there any better solution that can deal with this and be portable?

Well not really, but if overflow is your highest priority, then

#include <limits.h>
#include <time.h>

double monotimer (void (*something) (void * p), void * p) {
double dt, cdt;
time_t start = time (NULL), end;
clock_t cstart = clock(), cend;

something (p); /* Whatever you are timing */

dt = difftime (end = time (NULL), start);
cdt = (cend = clock ()) - cstart;
ock must have wrapped around (via difftime()) and simply offset that
to the clock difference (after casting to a large enough type, like
double or
if (dt >= floor (((double) ULONG_MAX) / CLOCKS_PER_SEC)) return
dt;
return cdt / (double) CLOCKS_PER_SEC;
}

So after around 50 days of running time you will switch from cycle
timer to wall clock time on Unix systems. On Windows both just
measure wall clock time in different units. So on Windows you could
do more by trying to calculate how many times the clock wrapped around
(after casting it to a double or an int64_t).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top