Should I Stop Stopwatch at the end of the method?

六月ゝ 毕业季﹏ 提交于 2019-12-04 14:55:06

问题


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.


回答1:


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




回答2:


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 from the memory used by the object itself, of course)!

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 real curiosity about the implementation details: read this post.




回答3:


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



来源:https://stackoverflow.com/questions/24140261/should-i-stop-stopwatch-at-the-end-of-the-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!