Millisecond clock resolution for DateAndTime now

Ned Konz ned at squeakland.org
Thu Sep 30 04:25:37 UTC 2004


On Tuesday 21 September 2004 5:49 pm, Avi Bryant wrote:
> You don't need to know the max value - you just need to know that it
> has rolled over (and you have to make sure that you check frequently
> enough that you'll catch every rollover).  Then you recalibrate from
> scratch, ie, by repeatedly watching for the second clock to change and
> recording the millisecond clock value at that point.  Of course, this
> means that every once in a while "DateAndTime now" will be very slow;
> need to deal with that somehow.

Actually, I deal with this all the time in my microcontroller code, and it's 
simple to make it fast.

If you assume that:
- the millisecond clock rate is accurate (which it had better be!)
- the millisecond clock is an unsigned number, limited to SmallInteger 
maxVal / 2 (which it is; it's masked with 16r1FFFFFFF)

then you can do this:

globals:

BigMillisecondClock is an arbitrary-precision integer

LastMillisecondClock is a SmallInteger, a copy of the millisecondClock the 
last time we looked at it

MaxMillisecondClockValue is the maximum value of the millisecond clock on this 
platform

from time to time (that is, more often than MaxMillisecondClockValue):

now := Time millisecondClockValue.
delta := now - LastMillisecondClock.
delta < 0 ifTrue: [ "wrapped"
 delta := delta + MaxMillisecondClockValue + 1 ].
BigMillisecondClock := BigMillisecondClock + delta.
LastMillisecondClock := now.

here's some examples:

last = 1
now = 4
delta = (4 - 1)
 = 3 (normal)

last = MaxMillisecondClockValue
now = 2
delta = (2 - MaxMillisecondClockValue) + MaxMillisecondClockValue + 1
 = 3 (wrapped)

-- 
Ned Konz
http://bike-nomad.com/squeak/



More information about the Squeak-dev mailing list