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?
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.
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.
ElapsedTicks
(no dot) refers to the number of ticks of the stopwatch, and therefore must be used in conjunction withStopwatch.Frequency
(this is not the same on all machines) to calculate the elapsed time.Elapsed.Ticks
(with a dot) gives the number ofTimespan
ticks and is independent of the stopwatch frequency.
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.
Use the Stopwatch class should do the trick.
The Stopwatch class is your best bet because of its accuracy:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
Example:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6167361.html
Besides System.Diagnostics.StopWatch also check this link: Multimedia Timer for .NET Framework . NTN
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!