Precise Time 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?

13.10.2009 20:57:58
This question seems to be a (worse) duplicate of…, but I like the answer better.
Abacus 19.12.2013 21:04:52

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.

12.08.2011 01:09:08

Use the Stopwatch class, should do the trick.

13.10.2009 21:01:42
13.10.2009 21:05:39

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.

25.04.2011 03:29:12
Note that Stopwatch may be inaccurate on a laptop due to power saving measures on the CPU, however a modern Intel i7 or newer wouldn't suffer from this problem. In other words, if you're doing timing on a work PC, things will be much more accurate.
Contango 14.02.2012 10:22:57

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!

23.05.2017 12:06:16