Is the timer resolution of the System.Diagnostics.

2019-03-03 15:12发布

问题:

.Net has support for high resolution timing using the System.Diagnostics.Stopwatch class. I understand that the specific resolution that this class uses differs depending on the underlying hardware and can be obtained via the static property Stopwatch.Frequency.

This frequency appears to be related to CPU frequency and Stopwatch reads this value and stores it in a static class variable within a static initializer/constructor. Hence I'm now wondering if this class will report incorrect timings if the CPU clock changes? e.g. in systems that alter the CPU clock depending system load.

回答1:

MSDN:

*The Frequency value depends on the resolution of the underlying timing mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Frequency value reflects the frequency of that counter. Otherwise, the Frequency value is based on the system timer frequency.*

The source of the Stopwatch.Frequency is not the CPU frequency. It is the frequency of a high frequency hardware counter. On windows this counter frequency is typically also read by a call to the QueryPerformanceCounter function while on linux High Resolution POSIX Timers are used to get high resolution timing.

The use of Time Stamp Counter (RDTSC - CPU frequency) is often discussed in this context but has no real relevance:

Some older hardware may not provide any high frequency hardware for timing purposes, thus the frequency of the CPU is used as a replacement. When using the CPU frequency for timing it needs to be secured that the frequency does remain constant. More modern hardware provides dynamic CPU frequency modification. Using the CPU freqency as a measure while it is dynamically modified would end in a messs.

Fortunately this is non existing situation. Systems which can modify their CPU frequency are more modern. Such modern systems also do have a separate high frequency timer hardware High Precision Event Timer.

There are some rumors about using the CPU frequency on multicore systems. In fact there has been a problem with certain hardware. But that's long time ago and fixed for some time.