INN timer code and time overflows

bill davidsen davidsen at tmr.com
Thu Oct 5 23:33:38 UTC 2000


In article <ylwvfq1ocd.fsf at windlord.stanford.edu> you write:
| 
| Hm.  Could someone remind me how unsigned arithmetic works?
| 
| I'm looking at the innd timer code and I think the timer values wrap in a
| long-running server.  gettime returns the number of milliseconds since the
| first time it was called (at the start of the lifetime of innd), and it's
| an unsigned int (32 bytes on most platforms).  That means the maximum
| timestamp it can return is 4294967295, or 4294967 seconds, which is about
| 50 days.  After that point, I think the arithmetic would overflow.
| 
| Does this just quietly work anyway?  If you subtract a very high unsigned
| number from a very low unsigned number, does it give you the right
| difference?  I can't quite wrap my mind around it.

  Doen't work. I've spent several months working on odd cases of this,
off and on, and it doesn't work. When new_time < old_time (unsigned) you
have to add the base (2^32 as you say) to the result to get the right answer.

  Now that's easy if the value is 32 bits and the compiler supports long
long, otherwise you have to add the largest power of two (again
unsigned) twice. Ugly.

  Even uglier is when the value may have rolled over more than once. I
am seeing that, and I have no way to catch it other than sample more
often. If you want to know the btes transferred every 15 min, it can be
>4G, so you measure at smaller times and add (not overflowing that, either).

  Fortunately, you can convert to double, add the constant, and convert
to int, losing at most a single count one way or the other.

  unsigned long oldtime, newtime;
  double d_old, d_new, d_k = 2<<30 * 4d0;
  int et;

  if (newtime < oldtime) {
  	d_old = oldtime;
  	d_new = newtime;
  	et = int(.5 + d_new - d_old + d_k);
  } else {
  	et = newtime - oldtime;
  }

  Or something like that...
-- 
bill davidsen <davidsen at tmr.com>
  CTO, TMR Associates, Inc
Doing interesting things with little computers since 1979.



More information about the inn-workers mailing list