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();
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.
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.
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.
Looking at the source code, it is not thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With