views:

419

answers:

3

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();
+5  A: 

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.

Michael
@Michael another thing that should be mentioned is that it will fallback to tickcount if QPC is not available
Sam Saffron
+2  A: 

This sounds like a recursive answer but the only way to truly know the penalty of Stopwatch is to measure it. Measuring managed code usually involves Stopwatch instances.

Stopwatch is only meant for diagnostic purposes though and should not be used in a retail application. Unless of course you are in a diagnostic mode. Hence this really shouldn't be an issue for non-diagnostic code. Can you provide some insight into your scenario so that we can give a better answer?

Stopwatch instances are built (usually) on top of a QueryPerformanceCounter call. These are not free but they're not terribly expensive either. Anything that's worth measuring with a Stopwatch will be a long enough running task that the cost of the task will make the QueryPerformanceCounter call insignificant. Otherwise, why are you measuring it?

JaredPar
+1  A: 

In my experience, there is some noticeable overhead when using the Stopwatch class. Certainly much more than using Environment.TickCount or such to measure time, but still not too great. However, this may or may not be a big problem for you. If the time period being measured is typically a very short one (as should usually be the case when using Stopwatch, given that other methods are just as good for timing longer periods), then performance shouldn't be affected perceptably, I'd imagine. Also, the end of this page has a bit to say about the cost of running a Stopwatch in your program. (Not sure I would take the advice on using it for constant program monitoring however.)

Noldorin