Brian Webster
Brian Webster

Reputation: 30865

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?

Upvotes: 3

Views: 8080

Answers (6)

Jay
Jay

Reputation: 3355

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.

See https://stackoverflow.com/questions/15725711/obtaining-microsecond-precision-using-net-without-platform-invoke

Let me know if you find otherwise!

Upvotes: 0

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

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.

Upvotes: 4

MusiGenesis
MusiGenesis

Reputation: 75346

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.

Upvotes: 7

Rubens Farias
Rubens Farias

Reputation: 57976

Besides System.Diagnostics.StopWatch also check this link: The Multimedia Timer for the .NET Framework. HTH

Upvotes: 1

Andy
Andy

Reputation: 5268

Use the Stopwatch class, should do the trick.

Upvotes: 3

Related Questions