This is slightly different, but I think clearly illustrates the logic involved.
I'm working on some MSP430 code in C, and have a timestamp struct very similar to timeval, but with nsecs instead of usecs.
This code keeps everything positive, so unsigned ints would work fine, and avoids overflows (I think). It also doesn't modify the timestamps/timevals being passed in, except the result of course.
typedef struct timestamp {
int32_t secs;
int32_t nsecs;
} timestamp_t;
int timestamp_sub(timestamp_t * x, timestamp_t * y, timestamp_t * result){
// returns 1 if difference is negative, 0 otherwise
// result is the absolute value of the difference between x and y
negative = 0;
if( x->secs > y->secs ){
if( x->nsecs > y->nsecs ){
result->secs = x->secs - y->secs;
result->nsecs = x->nsecs - y->nsecs;
}else{
result->secs = x->secs - y->secs - 1;
result->nsecs = (1000*1000*1000) - y->nsecs + x->nsecs;
}
}else{
if( x->secs == y->secs ){
result->secs = 0;
if( x->nsecs > y->nsecs ){
result->nsecs = x->nsecs - y->nsecs;
}else{
negative = 1;
result->nsecs = y->nsecs - x->nsecs;
}
}else{
negative = 1;
if( x->nsecs > y->nsecs ){
result->secs = y->secs - x->secs - 1;
result->nsecs = (1000*1000*1000) - x->nsecs + y->nsecs;
}else{
result->secs = y->secs - x->secs;
result->nsecs = y->nsecs - x->nsecs;
}
}
}
return negative;
}