views:

54

answers:

3

Hi, I'm trying to count the execution of function in my code (that takes over an hour), and I'm using clock(), but I'm getting some errors, since the time calculated is negative. I'm doing like this:

long double time;
clock_t start, t_end;

t_start = clock();
algorithm->execute();
t_end = clock();

time = ((long double) t_end - t_start) / CLOCKS_PER_SEC;

cout << time << endl;

I'm I doing something wrong? Thanks in advance.

+1  A: 

Have you checked to make sure neither call to clock() is returning -1?

The clock() function returns the processor time since the program started, or - 1 if that information is unavailable.

Another approach of doing this is:

#include <time.h>

time_t start, end;
time(&start);
algorithm->execute();
time(&end);
double diff = difftime(end, start);
Justin Ardini
I think that approach doesn't show miliseconds.. I need them
dmessf
Ah, didn't expect you would need milliseconds when it takes over an hour.
Justin Ardini
A: 

I'm not 100% sure, but do you cast only t_end to a long double ???

Shouldn't it be:

((long double)t_end - (long double)t_start)/CLOCKS_PER_SEC

or

((long double)(t_end - t_start))/CLOCKS_PER_SEC

???

TooAngel
+2  A: 

CLOCKS_PER_SEC is 1000000 and clock() returns a signed 32-bit value so will go negative after about 36 minutes and wrap after about 72 minutes.

See http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime for details on how to measure long execution times.

Dipstick
So.. after 72 minutes it gets "reseted"?
dmessf
`CLOCKS_PER_SEC` is not necessarily 1000000, it's the number of clock ticks in a second. That could be any number. Additionally, `clock()` returns a `clock_t`, which is just a type capable of representing tick counts. It's not necessarily signed or unsigned, or any bit-count.
GMan
@GMan - You are more or less correct. Posix requires CLOCKS_PER_SEC to be 1000000 so this will be the case for Linux (and most unix variations) but may not be the case for non-compliant systems - I understand that VC++ on Win32 uses a value of 1000.
Dipstick