Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Stopwatch really broken?

Tags:

.net

stopwatch

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?

like image 654
Jakub Šturc Avatar asked Apr 06 '10 14:04

Jakub Šturc


3 Answers

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.

like image 73
Andrew Hare Avatar answered Sep 28 '22 05:09

Andrew Hare


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".

like image 25
Cheeso Avatar answered Sep 28 '22 03:09

Cheeso


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.

like image 29
Michael Stum Avatar answered Sep 28 '22 03:09

Michael Stum