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?
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?
The 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:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
Example:
http://articles.techrepublic.com.com/5100-10878_11-6167361.html
Besides System.Diagnostics.StopWatch also check this link: The Multimedia Timer for the .NET Framework. HTH
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 Timespan
ticks, 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.