-2

What should be the best way to calculate the time diff which is accurate upto the level of Microseconds. currently I am doing as follows:

((TimeSpan)(DateTime.Now - _perfClock)).TotalMilliseconds

Note: perfClock is DateTime (set prior to task)

Which is suppose to give accuracy upto Milliseconds, but in my case it is showing values ends with "000". like 8000,9000 etc... This is forcing me to think that is just converting seconds to Milliseconds somewhere, instead of calculating diff in Milliseconds. (Possibly I am wrong somewhere in code above).

But what should be the recommended mechanism for accurate Time Diff calculation?

-Sumeet

Sumeet
  • 905
  • 1
  • 14
  • 32
  • 2
    I think you should look at [`Stopwatch`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) – V4Vendetta Jan 06 '12 at 06:07
  • title is misleading since your subtracting from a DateTime and not a TimeSpan – Chuck Savage Jan 06 '12 at 06:49
  • i belive subtracting from DateTime gives you a timespan – JasonS Jan 06 '12 at 06:52
  • @jaysun it depends: subtracting a TimeSpan from a DateTime gives you another DateTime; subtracting a DateTime from another DateTime gives you a TimeSpan. In the example, the type of _perfClock is not specified. – phoog Jan 06 '12 at 07:03

3 Answers3

2

The issue is not with TimeSpan, that is accurate down to ticks, which is 100 nanoseconds.

The issue is you are using DateTime.Now for your timer.

DateTime.Now is accurate to about 16ms i believe. as mentioned by V4Vendetta, you want to use Stopwatch if you need "high resolution" results. Stopwatch can provide you with ticks (long) or TimeSpan. use Timespan for easy manipulation (in your case, add/subtract).

Note also that Stopwatch provides a .IsHighResolution property, to see if you have a better accuracy than Datetime.Now (it's always true on PC iirc)

JasonS
  • 7,443
  • 5
  • 41
  • 61
0

I don't know the context in which you are measuring time but it would be good to start of with Stopwatch and check your results.

Also worth a read Precise Measurement

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

Have you tried:

TimeSpan diff = DateTime.Now.Subtract(_perfClock);
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69