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:

  • Tick generator
    It’s a piece of hardware that generates a special kind of event (ticks) at a constant frequency. In practice, the generator frequency can be changeable, but in most cases, it’s easier to imagine that the frequency is fixed. Typically, the generator is implemented with the help of a crystal oscillator (a small piece of quartz or other ceramic material).
  • Tick counter
    In modern computers, no data type expresses the actual time. We can only emulate it with basic data types like int or long. Hardware timers use a tick counter which is an integer value that counts how many ticks are generated by the tick generator. Each tick corresponds to a time interval (again, it’s easier to imagine that each tick corresponds to the same fixed time interval). Thus, the amount of ticks can be converted to a time interval.
  • Tick counter API
    It’s a programming interface that allows getting the current value of a tick counter from your software.


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. $$