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
.net time vb.net timing


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 to share


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 with Stopwatch.Frequency

    (this is not the same on all machines) to calculate the elapsed time.
  • Elapsed.Ticks

    (with a dot) gives the number of Timespan

    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.

+6


source to share


Use the Stopwatch class should do the trick.

+3


source to share


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

+2


source to share


Besides System.Diagnostics.StopWatch also check this link: Multimedia Timer for .NET Framework . NTN

+1


source to share


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 to share







All Articles
Loading...
X
Show
Funny
Dev
Pics