How accurate is System.Diagnostics.Stopwatch?

31,420

Solution 1

Why you don't profile your code instead of focusing on micro-benchmarks?

There are some good Open Source profilers like:

Solution 2

I've just written an article that explains how a test setup must be done to get an high accuracy (better than 0.1ms) out of the stopwatch. I Think it should explain everything.

http://www.codeproject.com/KB/testing/stopwatch-measure-precise.aspx

Solution 3

The System.Diagnostics.Stopwatch class does accurately measure time elapsed, but the way that the ElapsedTicks method works has led some people to the conclusion that it is not accurate, when they really just have a logic error in their code.

The reason that some developers think that the Stopwatch is not accurate is that the ElapsedTicks from the Stopwatch DO NOT EQUATE to the Ticks in a DateTime. The problem arises when the application code uses the ElapsedTicks to create a new DateTime.

var watch = new Stopwatch();
watch.Start();
... (perform a set of operations)
watch.Stop();
var wrongDate = new DateTime(watch.ElapsedTicks); // This is the WRONG value.

If necessary, the stopwatch duration can be converted to a DateTime in the following way:

// This converts stopwatch ticks into DateTime ticks.
// First convert to TimeSpan, then convert to DateTime
var rightDate = new DateTime(watch.Elapsed.Ticks); 

Here is an article that explains the problem in more detail: http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-ticks-are-not-timespan-ticks.aspx

Solution 4

Stopwatch class return different values under different configuration as Frequency depends on the installed hardware & operating system.

Using stopwatch class we can have only the rough estimation of execution time. And for each execution it returns different value so we have to take average of different execution.

More Info : http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

Solution 5

First, exact is of course not a possible or meaningful concept when talking about time or space, since no empyrical measurement of a physical magnitude can ever pretend to be exact.

Second, David Bolton's blog article may be useful. I'm quoting:

If this was timed with the high resolution counter then it will be accurate to microseconds. It is actually accurate to nanoseconds (10-9 seconds, ie a billionth of a second) but there is so much other stuff going on that nanosecond accuracy is really a bit pointless. When doing timing or benchmarking of code, you should do a number of runs and take the average time- because of other processes running under Windows, how much swapping to disk is occurring etc, the values between two runs may vary.

Share:
31,420
leora
Author by

leora

Updated on November 18, 2020

Comments

  • leora
    leora over 3 years

    How accurate is System.Diagnostics.Stopwatch? I am trying to do some metrics for different code paths and I need it to be exact. Should I be using stopwatch or is there another solution that is more accurate.

    I have been told that sometimes stopwatch gives incorrect information.

    • duffymo
      duffymo over 15 years
      Is millisecond accuracy enough? Should be sufficient for your purposes. Define "accurate".
    • leora
      leora over 15 years
      i know it can give you milliseconds but i have been told that there are many cases where its not accurate
    • brunocascio
      brunocascio over 15 years
      Don't ever rely on a single measurement of anything for accuracy. Run each code path for several minutes and count the number of iterations to get an average.
    • Ishmaeel
      Ishmaeel over 15 years
      Thanks for the question. I didn't even know there was such a class in the framework until now. Heh.
    • Thomas Maierhofer
      Thomas Maierhofer about 14 years
      I've written an article about that. It shows how you get good measurements out of the stopwatch class: codeproject.com/KB/testing/stopwatch-measure-precise.aspx
    • ToolmakerSteve
      ToolmakerSteve over 8 years
      BTW, since this is a very old question now, in newer .NETs running on newer hardware, stopwatch accuracy is much better, because (as Lee Grisholm says in a comment on Kernelman's answer), it is now a wrapper around QueryPerformanceCounter.
  • D'Arcy Rittich
    D'Arcy Rittich over 15 years
    I ran their sample code. It said it would be accurate to within 0 nanoseconds, and gave me a result of -657ms for one of the tests. Not very helpful!
  • Dennis Kioko
    Dennis Kioko over 15 years
    Precision and Accuracy are not the same thing. Your computer does not have nanosecond accuracy. It doesn't even have millisecond accuracy.
  • Jonathan Leffler
    Jonathan Leffler about 13 years
    Note that the NProf site at Google Code says NProf is no longer under development -- it recommends SlimTune instead.
  • Lee Grissom
    Lee Grissom over 12 years
    Looking at the source code for Stopwatch class (using .NET Reflector), it's already a very thin wrapper around QueryPerformanceCounter.
  • Jannes
    Jannes over 12 years
    Yes it does. Not always, but recent computers use the RDTSC CPU instruction. It can be accurate up to the frequency of the CPU (like 3 GHz). However, I'm having issues with some newer hardware where the StopWatch.Frequency is around 2MHz (so I'm guessing Windows is using some other clock on the motherboard), but for some reason that frequency is not very stable, leading to error into the milliseconds... which is why I'm browsing stackoverflow for it.
  • Jannes
    Jannes over 12 years
    Seconds is a lower case s. ms not mS. en.wikipedia.org/wiki/Second#SI_multiples (same in your article)
  • Thomas Maierhofer
    Thomas Maierhofer over 9 years
    The main problem is not disk I/O it is in fact thread context switches. With the newer versions of the .NET framework and Windows this problem has become less important, but it is still there.
  • A.R.
    A.R. about 9 years
    Useful information, but this is an answer for a different question.
  • Adam White
    Adam White over 7 years
    This does not answer the question, as stated.
  • Philm
    Philm about 7 years
    Answer to comments as "..does not answer the question" : On the contrary. This answers the question, if you read it: "Should I be using stopwatch or is there another solution that is more accurate". It only doesn't answer the headline of the question. Besides that, there are people here (as me) who see improvement suggestions as important and welcome answers, and for me this includes also references to alternative solutions. I have some problems to understand, why there seem to be not few people around here, who need to critisize that (?)
  • Philm
    Philm about 7 years
    Your article somewhat contradicts to what MS states here: msdn.microsoft.com/en-us/library/windows/desktop/… MSDN. They claim that for most hardware, Stopwatch() is fastest and accurate especially for multiprocessor CPUs and frequence-changing-CPUs (which are most modern CPUs I would guess). Do you still think, it is worth, to run time-manamgent on only one thread (if possible)?
  • Ed S.
    Ed S. about 5 years
    @Philm: Agreed, but it's unfortunate that this is the top Google result for "C# stopwatch resolution"