[lib] Fix time_elapsed()

The previous implementation was very naive and incorrect.
This commit is contained in:
Matteo Cypriani 2012-01-06 13:45:47 +01:00
parent 4dc45acff7
commit 93f316d2c6
2 changed files with 54 additions and 10 deletions

View File

@ -250,20 +250,63 @@ void owl_timestamp_to_string(char *const dst, const owl_timestamp src)
uint_fast32_t owl_time_elapsed_ms(const owl_timestamp d1,
const owl_timestamp d2)
{
return owl_timestamp_to_ms(owl_time_elapsed(d1, d2)) ;
owl_timestamp elapsed ;
owl_time_elapsed(&d1, &d2, &elapsed) ;
return owl_timestamp_to_ms(elapsed) ;
}
/*
* Returns a owl_timestamp storing the time between two dates.
* Computes the time difference between two owl_timestamp 'd1' and
* 'd2'.
* Note that it is a delay, not a simple substraction, therefore the
* result is always positive. The result is stored in the 'elapsed'
* argument.
*/
owl_timestamp owl_time_elapsed(const owl_timestamp d1,
const owl_timestamp d2)
void owl_time_elapsed(const owl_timestamp *const d1,
const owl_timestamp *const d2,
owl_timestamp *const elapsed)
{
owl_timestamp elapsed ;
elapsed.tv_sec = abs(d1.tv_sec - d2.tv_sec) ;
elapsed.tv_nsec = abs(d1.tv_nsec - d2.tv_nsec) ;
return elapsed ;
int_fast32_t sec, nsec ;
assert(d1) ;
assert(d2) ;
assert(elapsed) ;
sec = (int_fast64_t) d1->tv_sec - d2->tv_sec ;
nsec = (int_fast64_t) d1->tv_nsec - d2->tv_nsec ;
if (sec == 0)
{
elapsed->tv_sec = 0 ;
elapsed->tv_nsec = abs(nsec) ;
}
else if (sec > 0)
{
if (nsec >= 0)
{
elapsed->tv_sec = sec ;
elapsed->tv_nsec = nsec ;
}
else // nsec < 0
{
elapsed->tv_sec = sec - 1 ;
elapsed->tv_nsec = nsec + 1000000000ul ;
}
}
else // sec < 0
{
if (nsec > 0)
{
elapsed->tv_sec = abs(sec) - 1 ;
elapsed->tv_nsec = 1000000000ul - nsec ;
}
else // nsec <= 0
{
elapsed->tv_sec = abs(sec) ;
elapsed->tv_nsec = abs(nsec) ;
}
}
}

View File

@ -221,8 +221,9 @@ uint64_t owl_timestamp_to_ms(const owl_timestamp d) ;
void owl_timestamp_to_string(char *const dst, const owl_timestamp src) ;
uint_fast32_t owl_time_elapsed_ms(const owl_timestamp d1,
const owl_timestamp d2) ;
owl_timestamp owl_time_elapsed(const owl_timestamp d1,
const owl_timestamp d2) ;
void owl_time_elapsed(const owl_timestamp *const d1,
const owl_timestamp *const d2,
owl_timestamp *const elapsed) ;
// Endianess
owl_timestamp owl_hton_timestamp(const owl_timestamp d) ;