I need access to very precise timing in a .NET application.
I need microsecond precision.
Is there an easy way to do this in .NET?
Stopwatch class is the best precision that you can get, it uses the high frequency timer.
The frequency of the stopwatch depends upon the frequency of the CPU, but its usually in the millions times per second range.
If the CPU doesn't provide high frequency timer, then the class will fallback to system timer which is in the range 100-50 times per second.
The Stopwatch class is your best option due to it's accuracy:
System.Diagnostics.Stopwatch is the right class for this degree of granularity in your timing, but make sure you use your Stopwatch object's
Elapsed.Ticks property instead of its
ElapsedTicks property, as they are two different things.
ElapsedTicks(without the dot) refers to the number of ticks of the Stopwatch, and thus needs to be used in concert with
Stopwatch.Frequency(which is not the same on all machines) to calculate the elapsed time.
Elapsed.Ticks(with the dot) gives the number of
Timespanticks, and is not dependent on the Stopwatch frequency.
This is probably one of the subtlest potential errors in .Net.
Also, beware that Stopwatch is highly granular, but it isn't necessarily all that accurate (depending on your definition of the term). The elapsed time returned by Stopwatch will tend to drift away from the system time.
On my laptop, Stopwatch runs almost 5 seconds ahead over 24 hours, and this effect is even worse on some other machines.
If you're timing short durations, of course, this effect should not matter much at all.
I have found a method which works slightly more precisely then StopWatch, PerformanceCounters and every other implementation I come across and does not require Platform Invoke or otherwise.
Let me know if you find otherwise!