I’ve been using Stopwatch (and blogged about it) for some time and it never occurred to me to check how it really works. When using it as a benchmarking tool the fact that perhaps it wasn’t as accurate as can possible be didn’t bother me at all.
The question of the accuracy of Stopwatch become relevant in one of my pet projects, I needed a high precision timer and I wanted to know if it was up to the task.
Investigating Stopwatch proved to be very easy – using Reflector and I’ve opened System.Diagnostics.Stopwatch:
After a little pocking around I found that the actual “time keeping” is done in the GetTimeStamp() method that is used to get the current time for calculating the amount of time that passed. Diving into that method showed the following code:
It seems the method uses QueryPerformanceCounter (from Kernel32.dll) if it supported and uses .NET DateTime and a fall through if not.
QueryPerformanceCounter is a Windows API used to get the current value of the high-resolution performance counter directly from the processor. In fact in the past I used to use QueryPerformanceCounter for the purpose of high precision time related calculation.
Stopwatch handles all of the voodoo of initializing the related information (timer tick frequency) in its static constructor (cctor).
After this little research I know that I will no longer need to implicitly use PInvoke when I’m in need of high resolution timers.