Using Stopwatch class in C#
Stopwatch class may seem like primitive class that makes some date math behind the scenes but it actually doesn't hold true. With Stopwatch class it is possible to make very accurate measurements if operating system and computer hardware support high-resolution performance counter. If counter is not supported then fallback to simple date math is made.
Let's see simple program that uses Stopwatch class.
This code can be written a little shorter.
Notice one important thing: timer is stopped before time elapsed is written out. If we leave timer running the result is probably not the same.
Checking for high resolution mode
If something depends on if Stopwatch is using high resolution mode then IsHighResolution() of Stopwatch class can be called like shown in the following example.
Starting and stopping stopwatch
Stopwatch is better than primitive date math also because it's possible to stop and reset it. Stopping means that internal clock doesn't tick. Reset means that ticks clock is set to zero and counting of ticks starts over.
Next example uses short for-loop to wait one second while stopwatch is running and one second when stopwatch is stopped. In total the example runs around four seconds. As time is counted only for two waits then stopwatch reports elapsed time as something around two seconds.
Helper method for measuring code running time
Now let's write simple helper method that measures for how long given delegate expression runs.
- Find out for how long your method runs (Gunnar Peipman)
- Stopwatch class documentation (MSDN)
- Stopwatch class source code (.NET Framework 4.7 Reference Source)