Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Which PC timer most accurate?

402 views
Skip to first unread message

James Harris

unread,
Jun 5, 2009, 3:21:16 PM6/5/09
to
AIUI a standard PC, when running, has at least two timers:

one via the PIT fed from a 1.193182 MHz crystal
one via the RTC fed from a 32.768khz crystal

the two being entirely independent.

Anyone have any comments as to which is likely to be the most accurate
and thus the best source for time while a PC is running?

Would anyone go to the lengths of averaging the two or using one as a
check on the other?

James

Teodor Väänänen

unread,
Jun 6, 2009, 7:59:41 AM6/6/09
to

Another question which comes to mind with the PIT vs. the RTC is if the
clock of the PIT is accurate enough to give reasonable timings when used
to get the time difference between two events.

My working idea is to use the PIT for timeslicing when applicable
(single-CPU system) and fine-grained timing, while using the RTC for
time-of-day.

A question related to the RTC is how likely the CPU is to miss an
interrupt from it, I'm in the process of deciding whether to have the
RTC ISR simply incrementing a count of seconds since 1 Jan 1970 (i.e.
time_t) or whether to read out the BCD time to an array, and do the
conversion to time_t when the time-of-day is actually requested. Yet
another alternative is the incrementing method with occational syncs to
the BCD time.

/T.

--
Teodor V��n�nen | Don't meddle in the affairs of wizards,
<teostup...@algonet.se> | for you are good and crunchy with
http://www.algonet.se/~teodor/ | ketchup.
Remove stupidity to reply. |

Maxim S. Shatskih

unread,
Jun 6, 2009, 12:24:53 PM6/6/09
to
> RTC ISR simply incrementing a count of seconds since 1 Jan 1970 (i.e.
> time_t)

time_t is obsolete, I would suggest, for instance, Windows 64bit time (FILETIME aka native NT time).

Also don't forget HPET, which is by far better choice for a precision timer.

--
Maxim S. Shatskih
Windows DDK MVP
ma...@storagecraft.com
http://www.storagecraft.com

Rod Pemberton

unread,
Jun 6, 2009, 5:33:39 PM6/6/09
to
"James Harris" <james.h...@googlemail.com> wrote in message
news:8c9c69a0-b269-40cc...@j18g2000yql.googlegroups.com...

> AIUI a standard PC, when running, has at least two timers:
>
> one via the PIT fed from a 1.193182 MHz crystal
> one via the RTC fed from a 32.768khz crystal
>
> the two being entirely independent.
>
> Anyone have any comments as to which is likely to be the most accurate
> and thus the best source for time while a PC is running?
>

Other than the two links I posted in your "Resolution of wall-clock
real-time ticks" in January?...

I'd say that's dependent on a few things: 1) which supports the higher
frequency 2) which is more stable 3) are you reprogramming them.

From the summary below, if reprogrammed, it seems the maximum frequency for
the RTC is 8.192KHz, and the maximum frequency for the PIT is 1.193182Mhz.
If not reprogrammed, then you have 1.024KHz for RTC, 18.2065Hz for the PIT
TOD counter #0, or 66.287KHz for the PIT RAM refresh counter #1.


My timer summary:

DRAM (Dynamic Random Access Memory) refresh
- introduced on ?
- upto roughly 62.5KHz
- possibly at 15.825ms
- I/O port 61h bit 4 (undocumented?)

RTC (Real Time Clock)
- introduced on AT
- 32.768KHz crystal is used
- supports other crystals: 4.19Mhz, 1.05Mhz
- programmable resolutions of:
- 2, 4, 8,..., 4.096, 8.192 KHz for 32.768KHz crystal
- typically programmed for 1024Hz
- uses I/O ports 70h, 71h

PIT (Programmable Interrupt Timer) resolution of
- 8253 introduced in PC
- 8254 introduced in AT
- 1.193182MHz clock from 14.31818Mhz crystal (div 12)
- counter zero TOD (Time of Day) is 18.2065Hz from 1.193Mhz (div 65536)
- counter one RAM refresh set to divide by 12h, or approx. 15ms, 66.287KHz
- 16-bit timers
- overhead due to I/O delay of 1us
- uses I/O ports 40h to 43h
- used by MS Win2k QPC call

LAPIC (Local APIC) timer
- introduced with Intel SMP chipsets for Pentium Pro or later
- clocked at bus frequency
- timer on local cpu only
- 32-bit timer
- progammable clock divide by 1,2,...,128
- memory mapped I/O registers - address set by BIOS (default at FEE00xxxh)
- (I/O APIC memory mapped - address set by BIOS, default at FEC0000h)

ACPI PMT (Power Management Timer)
- ACPI 1.0 as required by MS' PC 97
- 3.579545Mhz clock
- counter increases once per clock
- overhead due to I/O delay of 1us
- on I/O port setup by BIOS
- 24-bit or 32-bit timer
- not affected by power management events
- uses ACPI registers (?)
- used by MS WinXP QPC call
- used by Linux

TSC (cpu TimeStamp Counter)
- RDTSC instruction on Pentium or later cpu's
- 64-bit counter
- one count per cpu clock
- overhead of 11 clocks
- Efficeon updates TSC counters at maximum frequency
- Efficeon doesn't properly update at actual cpu clock speed
- TSC drifts on AMD K8 and dual-core platforms
- TSC is not frequency independent on AMD K8 and dual-core
- used by Linux
- used by MS Vista
- used by MS SMP HAL Windows
- RDTSCP instruction on AMD NPT 0F, e.g., F, AM2, S1g1 cpus
- can affected by power management events
- bit returned by CPUID indicates power invariant

HPET (High Precision Event Timer)
- available on Intel ICH8 or later chipsets
- "multi-media timer"
- 10Mhz crystal or higher
- upto eight 64-bit counters, cpu dependent
- 64-bit counters can be used as 32-bit counters
- each counter has own clock input
- 1K of memory mapped I/O registers - address set by BIOS
- used by Linux


HTH,


Rod Pemberton


Cyril Novikov

unread,
Jun 6, 2009, 5:32:41 PM6/6/09
to
Maxim S. Shatskih wrote:
>> RTC ISR simply incrementing a count of seconds since 1 Jan 1970 (i.e.
>> time_t)
>
> time_t is obsolete, I would suggest, for instance, Windows 64bit time (FILETIME aka native NT time).

What exactly makes time_t obsolete? By POSIX definition, it's a value
containing time in seconds, width unspecified. I don't think seconds are
obsolete?

An advice to use Windows 64bit time in a custom OS is especially funny.

Cyril Novikov

unread,
Jun 6, 2009, 6:10:39 PM6/6/09
to
James Harris wrote:
> AIUI a standard PC, when running, has at least two timers:
>
> one via the PIT fed from a 1.193182 MHz crystal
> one via the RTC fed from a 32.768khz crystal
>
> the two being entirely independent.
>
> Anyone have any comments as to which is likely to be the most accurate
> and thus the best source for time while a PC is running?

The main accuracy problem with interrupt-driven timekeeping is the fact
that most of the time, timer frequency does not divide evenly by the
interrupt rate per second.

E.g. if you want to obtain a rate of 1000 ticks per second with the PIT,
the best you can do is set the interrupt period to 1193 cycles and thus
achieve ~1000.15 ticks per second. If you assume you have 1000 tps, your
time would run ahead by 182 PIT cycles each second, accumulating to 13
seconds drift per day.

This can be avoided by either admitting that your tick rate is not a
whole number and adjusting your timekeeping accordingly (this is not as
easy as it may sound, 64-bit multiplications/divisions may pop up all
around your 32-bit kernel), or using an even divider of the hardware
timer frequency for your system tick frequency.

Speaking of which, PIT's 1193182Hz is 2*41*14551. Not really convenient.
RTC's 32768Hz, on the other hand, lets one use any power of 2 up to 8192.

Wolfgang Kern

unread,
Jun 7, 2009, 3:43:37 AM6/7/09
to

James Harris wrote:

RTC is designed to show the correct time of day ...
What I use since many years is a PIT setting to 'about' 1 mSec and I
added a real time part (0..999 mS synchronised every second by RTCL).
Even the last milliSecond is a bit shorter or the zero-millisecond will
sometimes occure twice, it's anyway close enough for event marking
in real-time terms like file-age and similar.

All other timer/counters like delays, hardware timeout and time-slicer
run at the ~1.00015 MilliSecond without causing problems.

You could set the RTCL to interrupt at a rate of 1/1024 Seconds which
is more accurate, even harder to display in decimal than my '.999'.

__
wolfgang

James Harris

unread,
Jun 7, 2009, 11:34:37 AM6/7/09
to
On 6 June, 22:33, "Rod Pemberton" <do_not_h...@nohavenot.cmm> wrote:
> "James Harris" <james.harri...@googlemail.com> wrote in message

>
> news:8c9c69a0-b269-40cc...@j18g2000yql.googlegroups.com...
>
> > AIUI a standard PC, when running, has at least two timers:
>
> >   one via the PIT fed from a 1.193182 MHz crystal
> >   one via the RTC fed from a 32.768khz crystal
>
> > the two being entirely independent.
>
> > Anyone have any comments as to which is likely to be the most accurate
> > and thus the best source for time while a PC is running?
>
> Other than the two links I posted in your "Resolution of wall-clock
> real-time ticks" in January?...

Yes, different question. Maybe it wasn't too clear but I was looking
for comments on which of the two sources would keep time most
accurately in the long term.

> I'd say that's dependent on a few things: 1) which supports the higher
> frequency 2) which is more stable 3) are you reprogramming them.

Frequency is not too much of an issue in this case but accuracy is.
Stability, yes. Reprogramming, no. I'd just use an interrupt - IRQ0 or
IRQ8 - to keep the time-of-day clock updated.

While the machine is off it has to keep time via the RTC. But when
powered up we have a choice.

I guess it comes down to which crystal oscillator can be expected to
keep time most accurately.

...

James

James Harris

unread,
Jun 7, 2009, 1:14:55 PM6/7/09
to
On 6 June, 12:59, Teodor Väänänen

<use.instructions.in.signat...@invalid.invalid> wrote:
> James Harris wrote:
> > AIUI a standard PC, when running, has at least two timers:
>
> >   one via the PIT fed from a 1.193182 MHz crystal
> >   one via the RTC fed from a 32.768khz crystal
>
> > the two being entirely independent.
>
> > Anyone have any comments as to which is likely to be the most accurate
> > and thus the best source for time while a PC is running?
>
> > Would anyone go to the lengths of averaging the two or using one as a
> > check on the other?
>
> Another question which comes to mind with the PIT vs. the RTC is if the
> clock of the PIT is accurate enough to give reasonable timings when used
> to get the time difference between two events.

Both may be slow to read. You may be better off using another timer
for event durations.


> My working idea is to use the PIT for timeslicing when applicable
> (single-CPU system) and fine-grained timing, while using the RTC for
> time-of-day.
>
> A question related to the RTC is how likely the CPU is to miss an
> interrupt from it, I'm in the process of deciding whether to have the
> RTC ISR simply incrementing a count of seconds since 1 Jan 1970 (i.e.
> time_t) or whether to read out the BCD time to an array, and do the
> conversion to time_t when the time-of-day is actually requested. Yet
> another alternative is the incrementing method with occational syncs to
> the BCD time.

Why might an interrupt from the RTC be missed?

James

Rod Pemberton

unread,
Jun 7, 2009, 3:14:46 PM6/7/09
to
"James Harris" <james.h...@googlemail.com> wrote in message
news:c4fb828c-6c3c-4c9f...@m19g2000yqk.googlegroups.com...

On 6 June, 22:33, "Rod Pemberton" <do_not_h...@nohavenot.cmm> wrote:

1)


> I guess it comes down to which crystal oscillator can be expected to
> keep time most accurately.

2)


> Frequency is not too much of an issue in this case but accuracy is.

I don't understand how these two constraints are different for a clock
derived from a crystal: frequency and accuracy. Isn't the accuracy of a
crystal's frequency a small percent of it's frequency? Or, isn't the
accuracy of a crystal a number of cycles of possible deviation from it's
base frequency? I.e., in general, the higher the clock frequency the
smaller the time period will be for the clock's variation, deviation, or
inaccuracy. E.g., higher frequency = improved accuracy.

For a clock not derived from a crystal, I can understand frequency and
accuracy possibly being independent. But, from what I found, these both
have (or historically had) clocks derived from a crystal oscillator. I'd
guess that even on many modern motherboards, the clocks should still start
from a crystal source, even though that crystal is likely much higher in
frequency, and likely goes through many dividers first to get the desired
clocks. Of course, I haven't taken a close look at this motherboard. The
BIOS settings sort of imply that the motherboard clocks might not be from a
crystal, hinting that they may be from a digitally programmable oscillator
due to the very fine frequency control... However, I know the older
motherboards I had have crystals.


Rod Pemberton


Alexei A. Frounze

unread,
Jun 7, 2009, 8:33:59 PM6/7/09
to
On Jun 5, 12:21 pm, James Harris <james.harri...@googlemail.com>
wrote:

Whichever you choose, it usually goes down the toilet in a virtualized
environment as the interrupts get lost or attain extra jitter and the
maximum rates for the interrupts and counters get limited by the host
(explicitly and/or due to the workload). And then if you use at some
point something like TSC, you may encounter that its rate changes with
the CPU's C states and it may count up independently on different
processors in an MP system. Migrating threads between CPUs in such an
environment is a funny thing -- you may see the time go backward. :)

Alex

Maxim S. Shatskih

unread,
Jun 8, 2009, 4:12:14 AM6/8/09
to
> What exactly makes time_t obsolete? By POSIX definition, it's a value
> containing time in seconds, width unspecified. I don't think seconds are
> obsolete?

Time value with 1 second precision is obsolete relict from 1970ies.

UNIXen have some smarter value for time (and a set of syscalls for it) since at least 1990ies, so is Windows which was actually never using time_t in anything except the C runtime's functions intended only to port ancient non-Windows code to Windows.

Before FILETIME, MS was using the MS-DOS time which is the same level of stupidity as time_t.

> An advice to use Windows 64bit time in a custom OS is especially funny.

FILETIME/NT time is just the format, which you can reuse with ease without reusing Windows code. It is just better format then the stone-age time_t.

Maxim S. Shatskih

unread,
Jun 8, 2009, 4:31:19 AM6/8/09
to
>I guess it comes down to which crystal oscillator can be expected to
>keep time most accurately.

NTP is the only choice, all of the crystals have drift and skew.

Maxim S. Shatskih

unread,
Jun 8, 2009, 4:33:02 AM6/8/09
to
> inaccuracy. E.g., higher frequency = improved accuracy.

Amazing conclusion. You forgot, for instance, manufacturing tolerances while making a crystal, thermal drift to which the quartz oscillators are subject to, and so on.

Maxim S. Shatskih

unread,
Jun 8, 2009, 4:35:12 AM6/8/09
to
> The main accuracy problem with interrupt-driven timekeeping is the fact
> that most of the time, timer frequency does not divide evenly by the
> interrupt rate per second.

How is the _accuracy_ (things like drift and skew) is influenced by the duration of the time unit used?

> achieve ~1000.15 ticks per second. If you assume you have 1000 tps, your
> time would run ahead by 182 PIT cycles each second, accumulating to 13
> seconds drift per day.

This is trivially avoidable _rounding_ errors.

Maxim S. Shatskih

unread,
Jun 8, 2009, 4:37:54 AM6/8/09
to
>Whichever you choose, it usually goes down the toilet in a virtualized
>environment

Correct.

All these TSC, HPET and RTC are _inaccurate_. If you need the real accuracy - then NTP is the only choice.

The choice between TSC and RTC should be governed by:

a) resolution. Yes, it is different.

b) the peformance costs of accessing the chip (HPET is fastest).

James Harris

unread,
Jun 8, 2009, 8:28:50 AM6/8/09
to
On 8 June, 09:31, "Maxim S. Shatskih" <ma...@storagecraft.com.no.spam>
wrote:

> >I guess it comes down to which crystal oscillator can be expected to
> >keep time most accurately.
>
> NTP is the only choice, all of the crystals have drift and skew.

Not all PCs are internet-connected.

Similarly, not all have access to a radio clock source or a GPS or
other clock source.

Of course if an OS has access to a reliable and accurate time source
it can be used to calibrate whatever internal clock is used - though
it cannot compensate for variations due to temperature.

James

Rod Pemberton

unread,
Jun 8, 2009, 12:50:29 PM6/8/09
to
> "Maxim S. Shatskih" <ma...@storagecraft.com.no.spam> wrote in message
news:h0iibu$28a7$1...@news.mtu.ru...

> > inaccuracy. E.g., higher frequency = improved accuracy.
>
> Amazing conclusion. You forgot, for instance, manufacturing tolerances
while making a crystal, thermal drift to which the quartz oscillators are
subject to, and so on.

Do either of those increase the frequency variation/deviation of a crystal
to the point that a higher frequency crystal has larger variation than a
lower frequency crystal? It's definately possible they do, but I've never
seen that. AFAIK, the accuracy always increases with frequency for
crystals. What's the point of manufacturing a crystal with a higher
frequency whose accuracy is worse than a lower frequency crystal? No one
would buy your crystal...


Rod Pemberton


James Harris

unread,
Jun 10, 2009, 9:09:37 AM6/10/09
to
On 8 June, 17:50, "Rod Pemberton" <do_not_h...@nohavenot.cmm> wrote:

...

> AFAIK, the accuracy always increases with frequency for
> crystals.

Is that right? I've been looking for info to either confirm or refute
but without success.

A local electronics supplier sells crystals with temperature stability
figures quoted in parts per million. Not sure how relevant this is but
while ALL the other figures are 30 to 50 ppm their 32768Hz crystal is
rated at 15ppm.

This sounds like the 32kHz crystal is more stable than the others ...
but then again stability is not the same thing as accuracy.

James

Rod Pemberton

unread,
Jun 10, 2009, 2:55:19 PM6/10/09
to
"James Harris" <james.h...@googlemail.com> wrote in message
news:21d93491-5159-4301...@x3g2000yqa.googlegroups.com...

> On 8 June, 17:50, "Rod Pemberton" <do_not_h...@nohavenot.cmm> wrote:
>
> A local electronics supplier sells crystals with temperature stability
> figures quoted in parts per million. Not sure how relevant this is but
> while ALL the other figures are 30 to 50 ppm their 32768Hz crystal is
> rated at 15ppm.

From Mouser:

32.768KHz crystals
frequency tolerance in ppm 10,20,30,50
frequency stability in ppm 0.006,0.04,0.045,20,50,100

14.31818MHz crystals
frequency tolerance in ppm 20,30,45,50
frequency stability in ppm 5,20,30,50,100

- frequency tolerance is deviation at ambient temperature (25degC)
- frequency stability is deviation from ambient temperature (25degC) over
the defined operating temperature range (0degC to 70degC standard)
- crystals are affected by ageing, circuit capacitance, crystal cut, type of
encapsulation, etc. etc. etc.

From Anderson Electronics:
http://www.aextal.com/tutorial-specifying-frequency-stability.htm
http://www.aextal.com/tutorial-frequency-stability.htm
http://www.aextal.com/tutorial-cut.htm

Circuit Cellar Ink crystal information series:
http://www.circuitcellar.com/library/print/0298/bujanos91/index.htm

http://www.icmfg.com/faqs.html

> This sounds like the 32kHz crystal is more stable than the others ...
> but then again stability is not the same thing as accuracy.

It looks to me like the choice of AT and BT cut has an important effect on a
crystal's use as a timebase. CC's article indicates BT's are usually found
for crystals below 1MHz, like the 32.768KHz. The article also indicates
that BT cut crystal's are _not_ a good choice for a timebase. It seems the
temperature effects on frequency deviation of BT cut crystals accumulate
instead of averaging out with temperature variation like AT cut crystals. I
don't how to tell from Mouser's info what cut or mode those (modern)
crystals are. But, it seems likely to me, that 32.768KHz crystals are BT
cut and the 14.31818MHz crystal are AT cut. I.e., I still think the higher
frequency crystal has a more stable timebase. Unfortunately, from those,
there's no historical information from those on what type of crystals have
been used in PCs, or are whether either are currently used in PCs. I.e.,
did the designers choose high precision, or cheapest crystal available at
the time? I.e., are only lower quality crystals available in the secondary
markets as supplied by Mouser? I.e., were so many variations of tolerance
and stability available in 1980's? 1990's?

> > AFAIK, the accuracy always increases with frequency for
> > crystals.
>
> Is that right? I've been looking for info to either confirm or refute
> but without success.
>

Well, you can decide... Hey, here's an idea. For a modern motherboard, you
should be able to check the accuracy of both by using one of the other
timers. Yes? Of course, the result might just be that all system clocks
for new motherboards are derived from the same single clock... On an older
system, someone could attach some counter circuits to both clocks and see
how much they differ after a month.


Rod Pemberton


James Harris

unread,
Jun 12, 2009, 7:31:08 AM6/12/09
to
On 10 June, 19:55, "Rod Pemberton" <do_not_h...@nohavenot.cmm> wrote:

...

> It looks to me like the choice of AT and BT cut has an important effect on a


> crystal's use as a timebase.  CC's article indicates BT's are usually found
> for crystals below 1MHz, like the 32.768KHz.  The article also indicates
> that BT cut crystal's are _not_ a good choice for a timebase.  It seems the
> temperature effects on frequency deviation of BT cut crystals accumulate
> instead of averaging out with temperature variation like AT cut crystals.  I
> don't how to tell from Mouser's info what cut or mode those (modern)
> crystals are.  But, it seems likely to me, that 32.768KHz crystals are BT
> cut and the 14.31818MHz crystal are AT cut.  I.e., I still think the higher
> frequency crystal has a more stable timebase.  Unfortunately, from those,
> there's no historical information from those on what type of crystals have
> been used in PCs, or are whether either are currently used in PCs.  I.e.,
> did the designers choose high precision, or cheapest crystal available at
> the time?  I.e., are only lower quality crystals available in the secondary
> markets as supplied by Mouser?  I.e., were so many variations of tolerance
> and stability available in 1980's? 1990's?

True. It seems we cannot tell in general which is likely to be better
just by looking at what crystals are available. I take your point
about 32768Hz crystals being more likely to be a BT cut but it seems
we cannot be sure what's in use in a given PC. This really brings me
back to the original question of opinion and what others decided to
use. I don't think there is a simple answer ... but there's enough
info here to make a choice.


> > > AFAIK, the accuracy always increases with frequency for
> > > crystals.
>
> > Is that right? I've been looking for info to either confirm or refute
> > but without success.
>
> Well, you can decide...  Hey, here's an idea.  For a modern motherboard, you
> should be able to check the accuracy of both by using one of the other
> timers.  Yes?  Of course, the result might just be that all system clocks
> for new motherboards are derived from the same single clock...  On an older
> system, someone could attach some counter circuits to both clocks and see
> how much they differ after a month.

The modern timers while being of higher resolution may be less
*accurate*. That said, if the PC has at least intermittent access to
the internet it would be possible to check against NTP and use that to
work out a periodic adjustment to whatever internal time source was
being used. Due to the NTP round trip time it would be poor at
determining small differences but would be good over longer periods.

The RTC might be a good choice for consistency as it keeps time both
when the PC is off and when it is on but it's worth bearing in mind
that

1. the crystal will be warmer when the PC is on
2. the user might adjust the time stored in the RTC when our OS is not
running and we wouldn't know
3. according to wikipedia some machines use the powerline to drive the
RTC when the power is on

http://en.wikipedia.org/wiki/Real-time_clock#Timing

James

Brendan

unread,
Jun 12, 2009, 11:32:12 AM6/12/09
to
Hi,

Some generic notes...

I'm not convinced that modern motherboards still use crystals for the
RTC and/or PIT; and I have had motherboards that gain or lose up to 30
minutes per day.

If you care about drift (long term accuracy) then at a minimum I'd use
a very wide integers. For example, you could have a 64-bit value that
is added to the system timer tick each IRQ, like this:

mov eax,[private_time_between_IRQs_low_dword]
mov ebx,[private_time_between_IRQs_high_dword]
add [private_fractions_of_a_millisecond_since_boot],eax
adc [public_milliseconds_since_boot_low_dword],ebx
adc [public_milliseconds_since_boot_high_dword],0

In this case small adjustments to
"private_time_between_IRQs_low_dword" would result in extremely small
changes in "milliseconds_since_boot", and (if properly calibrated)
results in very low drift regardless of how badly the timer itself
drifts. During boot, you can also account for drift that occurred
while the computer was turned off; and you could use NTP or manual
intervention to calibrate it.

There's a difference between "accuracy" and "precision". You can have
a very precise (e.g. 10 MHz) timer that is very inaccurate, and you
can have a very accurate timer that isn't very precise.

For extremely precise timing, you have to use the best timer that is
available, because the RTC and PIT are not very precise and everything
else isn't guaranteed to be present and/or usable. In order of
preference, I'd use RDTSC, then local APIC, then HPET, etc. The main
concern here is whether or not an IRQ is required (e.g. RDTSC and ACPI
timers can't generate an IRQ).

Note: In theory you can set the PIT to generate an IRQ every 828 ns
and/or set the RTC to generate an IRQ every 122 us. In practice most
chipsets aren't able to handle these frequencies and you lose IRQs -
partly due to the time it takes for things like sending the EOI (and
remembering that RTC costs several I/O port accesses per IRQ), partly
due to IRQ latency (e.g. kernel disabling IRQs for too long), and
mostly because it's "low speed" ISA/LPC stuff.

The other thing you'd want to consider is whether an IRQ is always
required, or only required sometimes. For some purposes it's a lot
better to dynamically set the timer when an IRQ is actually needed to
avoid taking CPUs out of sleep states (and reduce overhead) and
improve precision. For an example, use the PIT in "one shot" mode
instead of "periodic mode", and set the count so the IRQ to occurs
exactly when needed (if needed) and set the count to 65536 when the
IRQ isn't needed (if you need to know how much time passed while you
weren't using the IRQ).

Also, to improve the precision of some timers you don't need to wait
until an IRQ occurs - you can read the count at any time. For example,
you could configure the PIT or local APIC timer to generate an IRQ
every 1 ms, but when you need a more precise time you can read the
"remaining count" (while being careful of race conditions) to get the
time until the next IRQ should occur, and therefore get precision that
is close to 828 ns (for PIT) or up to about 1 ns (for local APIC with
1 GHz bus).

For some CPUs the speed of the TSC depends on which state the CPU is
in (sleep states, thermal throttling, etc). If the OS controls which
sleep state the CPU is in then the OS knows when the TSC speed will
change due to sleep states; and if the OS uses the local APIC "thermal
monitor" IRQ then the OS knows when the TSC speed was changed due to
thermal throttling. Therefore even when the TSC isn't "fixed
frequency" you can still use it for *extremely* precise timing (if you
don't need an IRQ). For precision, the TSC can't be beaten (for modern
CPUs it's capable of measuring fractions of a nanosecond). TSC drift
is a different story (but typically when you need extremely precise
time measurement you don't care much about drift, and when you do care
about drift you don't need extreme precision).

For situations like profiling (e.g. "read TSC, do something, read TSC
again, calculate TSC difference"), one way to avoid problems caused by
TSC differences between different CPUs in the same system is to have a
"virtual TSC" for each task/thread. In this case you keep track of
"CPU ticks that this thread has spent running", and when the thread
wants to know its virtual TSC you return "virtual_TSC =
ticks_spent_running + current_TSC - TSC_at_thread_switch". This has
other benefits - it dramatically reduces bad results caused by task/
thread preemption, it gives you a nice/accurate way of measuring the
CPU time each task/thread has used, and it lets you adjust for TSC
speed changes (as described above). Also, you can set the "TSD" bit in
CR4 (which can help to improve security by preventing some types of
"side channel attacks") and then use the general protection exception
handler to emulate the RDTSC instruction (set EDX:EAX to the virtual
TSC) when CPL=3 code tries use RDTSC.

Finally, from what I remember some CPUs have bugs with RDTSC, where
the lowest 32-bits rolls over and you read the wrong value before the
highest 32-bits are incremented. For example, you might read
0x00000000:0xFFFFFFFF, then 0x00000000:0x00000000, then
0x00000001:0x00000001. To avoid this problem, on some CPUs you need to
wrap RDTSC with something like:

rdtsc
.retry:
mov ebx,eax
rdtsc
cmp eax,ebx
jb .retry

Of course this is a job for the OS, as most application programmers
aren't aware of CPU bugs like this and just assume it works "as
advertised"...


Cheers,

Brendan

0 new messages