Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What, if any, is the resource penalty for using System.Diagnostics.Stopwatch?

For example

foo() //Some operation bound by an external resource. db,I/O, whatever.

vs.

var watch = new Stopwatch();
watch.Start();
foo()
var time = watch.ElapsedMilliseconds
watch.Stop();
like image 942
Ben McNiel Avatar asked Apr 27 '09 21:04

Ben McNiel


People also ask

What is System diagnostics stopwatch?

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

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 C#?

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


1 Answers

I believe Stopwatch is built on top of QueryPerformanceCounter, so each call results in a kernel transition. If foo() is very brief, the QPC overhead will dwarf it.

If you're using Stopwatch to measure short tasks, you should run foo() many times (like thousands), and use Stopwatch around the whole batch. Divide the total time by the number of runs to get average time for the task.

like image 83
Michael Avatar answered Sep 27 '22 18:09

Michael