The exact time in .NET.

I need to access a very precise timeline in a .NET application.

I need microsecond precision.

Is there an easy way to do this in .NET?

+2


source to share


6 answers


Stopwatch

grade - the best accuracy you can get is using a high frequency timer.
The stopwatch frequency depends on the processor frequency, but it is usually found a million times per second.



If the CPU does not provide a high frequency timer, then the class will drop the system timer, which is in the range of 100-50 times per second.

+4


source


System.Diagnostics.Stopwatch is the correct class for this granularity at your time, but make sure you use your Stopwatch object Elapsed.Ticks

instead of a property ElapsedTicks

, as they are two different things.

This is probably one of the most subtle potential errors in .Net.



Also, be careful that the stopwatch is highly detailed, but this is not always accurate (depending on your definition of the term). The elapsed time returned by the stopwatch will deviate from the system time.

On my laptop, the stopwatch runs almost 5 seconds ahead in 24 hours, and the effect is even worse on some other machines.

If you are counting on short periods of time, of course this effect should not matter much.

+6


source


Use the Stopwatch class should do the trick.

+3


source


+2


source


+1


source


I found a method that works a little more precisely than StopWatch, PerformanceCounters, and every other implementation I come across and does not require a platform call or otherwise.

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

Let me know if you find another!

0


source







All Articles