Tek Eye

C# High Resolution Timer

Timing is important for lots of the software that runs our modern world. Sometimes the timing needs to be very precise and at very small intervals. Fortunately, the Microsoft Windows Operating System (OS) has supported a high resolution timer for some time. A .NET program can access a high resolution timer via the Stopwatch class. This tutorial provides an overview of the Stopwatch class and a demo program in C#. The C# high resolution timer example provided here helps learn about precision timing for .NET programs.

Windows and Real Time

Windows was made orginally made for office based Personal Computers (PCs). Yet grew to run servers as well as the desktop and latop computers. Windows is used to successfully run high performance data centres and to control industrial processes, even though it is not a real time operating systems (RTOS). Why can Windows be used to run time critical processes?

It all depends on how fast something needs to be controlled, and how accurate the timing needs to be. If the software on Windows is running fast enough, and the timing requirements do not need to be 100% accurate all the time, just most of the time, then Windows can be very good at handling a time sensitive task.

Windows, Hardware and Timing

Windows is not developed in isolation from the PC hardware. Microsoft works with hardware and the hardware manufacturers to bring PC improvements to market. Microsoft has a Windows Hardware Compatibility Program to ensure that Windows is properly supported by computers. Microsoft's Hardware Compatibility Specification includes the requirement for a high-precision event timer. Alongside the use of a high resolution timer, the Central Processing Unit (CPU) in computers has exceeded gigahertz (GHz) speeds since the early 2000's (1GHz being one thousand million cycles per second). Therefore, PC hardware is able to support high resolution timing.

On of the common problems with reliable timing in Windows was due to the OS needing to access slow hard disks. There would be noticeable pauses due to hard disk accesses. Now that Solid State Drives (SSDs) have supplanted mechanical drives that issue has reduced. Plus, PCs having more memory, which reduces the need to page memory to and from disk.

A high precision timer, GHz CPUs and SSDs means that Windows PCs are very fast devices. There is no excuse for a Windows computer not to be able to handle millisecond timing, most of the time.

Using the .NET Stopwatch Class

With the .NET Stopwatch class measuring time intervals is straightforward. Start by creating an instance of Stopwatch (using System.Diagnostics;):

Stopwatch sw = new Stopwatch();

There is a property to determine if a high resolution timer is present, otherwise timing resolution is in the milliseconds: