Notes / Hardware Timer


The real time is continuous. Unfortunately, it is impossible to work with continuous time and measure arbitrary time intervals. In computer engineering, any time measurements are based on hardware timers. You may think about a hardware timer as about composition of the following three parts:


This construction allows measuring any time interval (with some limitations which will be discussed soon). Usually, the tick duration is fixed and pretty small, and it’s described in the timer documentation, or it can be obtained with the help of another API. Sometimes developers use the “jiffy” term for the duration of 1 tick.

An example. Let’s say that we can get the tick counter value via the GetCurrentTicks() method and the frequency of our tick generator is 64 Hz. It means that one tick is (1/64) s = 0.015625 s = 15.625 ms. Here is an example of measurements:

int startTicks = GetCurrentTicks();       // 100 ticks
SomeLogic();                              // Actual time: 0.5 s
int endTicks   = GetCurrentTicks();       // 132 ticks
int elapsedTicks = endTicks - startTicks; // 32 ticks
double ticksInSec = 1.0 / 64.0;           // 1 tick = 0.015625 s
double elapsedTimeInSec =                 // Measure elapsed time
    elapsedTicks * ticksInSec;            // 32 * 0.015625 s = 0.5s

Here the SomeLogic() method takes 0.5 seconds, but we don’t know it in advance, we want to get this value in the program. We get two timestamps (by calling GetCurrentTicks()): before and after the method invocation. Let’s say, the first value is 100 ticks, and the second one is 132 ticks. The difference between these timestamps is 32 ticks We can easily convert ticks to seconds because we know the frequency (64 Hz):

$$ \textrm{ElapsedTime} = \textrm{Ticks} \cdot \frac{1}{f} = 32 \cdot \frac{1}{64\textrm{Hz}} = 32 \cdot 15.625ms = 0.5s. $$