Should I Stop Stopwatch at the end of the method?

C#.NetStopwatch

C# Problem Overview


Let's imagine we have simple measurements using Stopwatch

public void DoWork()
{
    var timer = Stopwatch.StartNew();
    // some hard work
    Logger.Log("Time elapsed: {0}", timer.Elapsed);
    timer.Stop(); // Do I need to call this?
}

According to MSDN:

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

I'm not sure if I should call this method when I'm no longer interested with timer instance. Should I "clear up" using Stop method?

EDIT

Keep in mind that Logger.Log(..) costs nothing because timer.Elapsed is read before the logger logs.

C# Solutions


Solution 1 - C#

No, you don't need to stop it. Stop() just stops tracking elapsed time. It does not free up any resources.

Solution 2 - C#

No, there is no need to stop or clean it up.

Stopwatch does not use any unmanaged resources (if you thought of IDisposable). It actually does not use any resources at all (except the memory used by the object itself, of course)! It also does not consume any CPU while measuring the elapsed time!

In windows implementations of .NET (full .NET Framework, Mono, .NET Core), it just calls the QueryPerformanceCounter() Windows API when needed (on Start() and Stop() and when reading Elapsed) to retrieve a high resolution time stamp.

In Linux implementations of Mono and .NET Core, it uses clock_gettime function to retrieve a monotonic increasing time value.

To anyone with a real curiosity about the implementation details: read this post.

Solution 3 - C#

I think Stop is useful if you want to reuse the Elapsed value.

Solution 4 - C#

If your code doesn't need to calculate, then no need to use Stop().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDariuszView Question on Stackoverflow
Solution 1 - C#UriilView Answer on Stackoverflow
Solution 2 - C#Mohammad DehghanView Answer on Stackoverflow
Solution 3 - C#vvvView Answer on Stackoverflow
Solution 4 - C#funbrain9View Answer on Stackoverflow