Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How accurate is System.Diagnostics.Stopwatch?

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.

like image 331
leora Avatar asked Dec 26 '08 17:12

leora


People also ask

How accurate is the Stopwatch class?

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.

Why is Stopwatch not accurate?

Timing with a stopwatch has quite a large uncertainty (accuracy error) due to the problem of actually having to press the button at the right time to start and stop it. Human reaction time can be as much as 2or 3 tenths of a second.

Is Stopwatch thread safe?

Looking at the source code, it is not thread-safe.

Does Stopwatch affect performance?

The overhead of using Stopwatch is negligible. It just calls the Windows API function: QueryPerformanceCounter(). The overhead of using Stopwatch is negligible.


Video Answer


2 Answers

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

like image 144
Thomas Maierhofer Avatar answered Sep 22 '22 18:09

Thomas Maierhofer


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

like image 31
user3308241 Avatar answered Sep 22 '22 18:09

user3308241