I am writing a thread library, and when scheduling the threads I need to know how long they've been ready. Every Thread instance has a timeval _timeInReady
field, and when I push an instance to the ready queue I call this function:
void Thread::startTiming() {
gettimeofday(&_timeInReady, NULL);
}
When I want to check the current _timeInReady
value I call:
double Thread::getTimeInReady() const {
return TIME(_timeInReady.tv_sec,_timeInReady.tv_usec);
}
Where TIME is #define TIME(a,b) ((a*1000000) + b)
So that I get the total time in microseconds.
My problem is that for some reason, I get crazy negative values (such as -10293843) when I check that field after a while.
Any ideas? Thanks!
You should return the result as a 64-bit unsigned integer, as you want an integer microsecond result, not a fractional second (which would imply returning double
):
unsigned long long Thread::getTimeInReady() const
{
return (unsigned long long)_timeInReady.tv_sec * 1000000ULL +
(unsigned long long)_timeInReady.tv_usec;
}
Your system might have uint64_t
which is a more concise than unsigned long long
, or you could typedef
it.