Should I Stop Stopwatch at the end of the method?

后端 未结 4 2046
春和景丽
春和景丽 2021-02-06 20:23

Let\'s imagine we have simple measurements using Stopwatch

public void DoWork()
{
    var timer = Stopwatch.StartNew();
    // some hard work
    Lo         


        
相关标签:
4条回答
  • 2021-02-06 20:44

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

    0 讨论(0)
  • 2021-02-06 20:44

    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.

    0 讨论(0)
  • 2021-02-06 20:45

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

    0 讨论(0)
  • 2021-02-06 20:46

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

    0 讨论(0)
提交回复
热议问题