views:

155

answers:

3

At MSDN page for Stopwatch class I discovered link to interesting article which makes following statement about Stopwatch:

However there are some serious issues:

  • This can be unreliable on a PC with multiple processors. Due to a bug in
    the BIOS, Start() and Stop() must be executed on the same processor to get a correct result.

  • This is unreliable on processors that do not have a constant clock speed (most processors can reduce the clock speed to conserve energy). This is explained in detail here.

I am little confused. I've seen tons of examples of using Stopwatch and nobody mention this drawbacks. How serious is this? Should I avoid using Stopwatch?

+2  A: 

It is not broken it just has limitations. For most purposes (read: informal micro-benchmarking) StopWatch is fine to use simply because it is good enough for informal testing. For more formal purposes you would most likely want to roll your own instrumentation code as you would that much more invested in getting proper results.

Andrew Hare
+2  A: 

More interesting questions are :

  1. under what conditions will Stop() be executed on a different processor than Start()?
    .
    In most application scenarios, the answer is "none".

  2. under what conditions will the clock speed of a processor change during a measured interval?
    .
    In CPU-intensive benchmarks, "none".

Cheeso
In case of CPU intensive benchmarks you are probably right. But in case of asynchronous IO things may be completely different.
Jakub Šturc
A: 

See the notes in the MSDN Article:

On a multiprocessor computer, it does not matter which processor the thread runs on. However, because of bugs in the BIOS or the Hardware Abstraction Layer (HAL), you can get different timing results on different processors. To specify processor affinity for a thread, use the ProcessThread.ProcessorAffinity method.

Michael Stum