clock() returning negative value

Hi, i have a program that runs for severel hours and i'm using the clock function to extract some time data. But I recently notice some weird values and through debugging I found out that sometimes the clock funtion is returning a negative value that is messing my calculations. Does anyone know how can I fix this issue?

PS: I'm using codeblocks running on ubuntu 11.01

Thanks in advance.
Bruno.
In http://cplusplus.com/reference/clibrary/ctime/clock/ it is written that clock may return -1. Also, if you're storing your time in a type smaller than clock_t this could happen. Other than that, I have no ideas.
In my case I'm sure it's not returning -1 and I don't know if it's a matter of variable type either, cause I'm storing in a float variable that I think it's big enought for the return of clock function. Besides i also have put the return of clock() in a debug watch and I still get a negative number.

But thanks.
Last edited on
If the program runs long enough the type will no longer be able to represent the number correctly so maybe the time wraps around and becomes negative.
So I'll try with the clock_t as hamsterman said and I'll report back to you...

Thanks.
Do you only get this when the program runs for a long time? You could cout the time every once in a while to see how it changes.
I was able to fix the problem using clock_t...

My code is like this now, for those with similar problem:

1
2
3
4
5
6
clock_t beginTime = clock();

//Do something here

double totalTime = (double)(clock()-beginTime)/CLOCKS_PER_SECOND;


The only way I could make this work was by casting the calc (clock()-beginTtime) to double, otherwise it doesn't work. I guess without the cast it tries to make all the calculations converting the values to int.

Thank you guys for the quickly help!
Bruno.
Last edited on
Topic archived. No new replies allowed.