我应该在方法的最后停止秒表吗?

假设我们使用 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?
}

根据 MSDN:

在典型的 Stopwatch 场景中,调用 Start 方法 然后最终调用 Stop 方法,然后使用 Elapsed 属性检查运行时间。

当我不再对计时器实例感兴趣时,我不确定是否应该调用这个方法。我应该使用 Stop方法“清理”吗?

剪辑

请记住,Logger.Log (. .)不需要花费任何成本,因为 timer.Elapsed是读取日志记录器日志 之前的。

30932 次浏览

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

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

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.

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