Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time in 1ms increments

The x86 interrupt 0x1A seems to give the computer's clock time, but it can only give accurate time to within 55ms (AH=0). Is there any way to get smaller increments (and maybe a bit more "normal") than that, like maybe 1ms? I'm trying to make my own toy OS, so i can't use anything i can't write myself.

like image 538
nuju Avatar asked Jul 19 '12 23:07

nuju


2 Answers

You can use the rdtsc (read timestamp counter) instruction on x86 to get the 64-bit CPU timestamp into edx:eax. The implementation of this instruction depends on your processor, but it either increments once per clock or at a constant rate. Because of this, the time resolution also varies, but it should be better than 1ms.

There are some caveats to using rdtsc:

  1. The timestamp counter is not necessarily in sync across CPU cores. This can be an issue in hyper-threaded and multi-core CPUs.
  2. The counter doesn't necessarily increment at a constant rate. It can be affected by throttling or power-saving features of the processor.
  3. Hibernation can cause the counter to reset.

Since you're writing your own OS, you might not need to worry about some of these issues.

like image 108
Chris Schmich Avatar answered Oct 31 '22 11:10

Chris Schmich


Since you're making your own OS, you don't have to keep the timer period. It is possible to reprogram the PIT to trigger INT 8 (IRQ 0) more often. See here.

On newer computers you can also make use of the High Precision Event Timer.

like image 36
Igor Skochinsky Avatar answered Oct 31 '22 11:10

Igor Skochinsky