首页 文章

计算方法的执行时间

提问于
浏览
403

可能重复:如何测量函数运行的时间?

我有一个I / O计时方法,可以将数据从一个位置复制到另一个位置 . 计算执行时间的最佳和最实际的方法是什么? ThreadTimerStopwatch ?还有其他方法吗?我想要最精确的一个,尽可能简短 .

5 回答

  • 57

    Stopwatch是为此目的而设计的,是衡量.NET中时间执行的最佳方法之一 .

    var watch = System.Diagnostics.Stopwatch.StartNew();
    // the code that you want to measure comes here
    watch.Stop();
    var elapsedMs = watch.ElapsedMilliseconds;
    

    Do not use DateTime测量.NET中的时间执行 .


    更新:

    正如@ series0ne在评论部分所指出的:如果您想要对某些代码的执行进行真正精确的测量,则必须使用内置于操作系统中的性能计数器 . following answer包含一个很好的概述 .

  • 17

    根据个人经验, System.Diagnostics.Stopwatch 类可用于衡量方法的执行时间,但是, BEWARE :它并不完全准确!

    Consider the following example:

    Stopwatch sw;
    
    for(int index = 0; index < 10; index++)
    {
        sw = Stopwatch.StartNew();
        DoSomething();
        Console.WriteLine(sw.ElapsedMilliseconds);
    }
    
    sw.Stop();
    

    Example results

    132ms
    4ms
    3ms
    3ms
    2ms
    3ms
    34ms
    2ms
    1ms
    1ms
    

    现在你想知道; "well why did it take 132ms the first time, and significantly less the rest of the time?"

    答案是 Stopwatch 不能补偿.NET中的"background noise"活动,例如JITing . 因此,第一次运行方法时,.NET JIT首先运行它 . 执行此操作所需的时间将添加到执行时 . 同样,其他因素也会导致执行时间发生变化 .

    你应该真正寻求绝对准确的是 Performance Profiling

    Take a look at the following:

    RedGate ANTS Performance Profiler是一种商业产品,但产生非常准确的结果 . - Boost the performance of your applications with .NET profiling

    这是关于分析的StackOverflow文章: - What Are Some Good .NET Profilers?

    我还写了一篇关于使用秒表进行性能分析的文章,你可能想看一下 - Performance profiling in .NET

  • 7

    StopWatch课程寻找最佳解决方案 .

    Stopwatch sw = Stopwatch.StartNew();
    DoSomeWork();
    sw.Stop();
    
    Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);
    

    它还有一个名为Stopwatch.IsHighResolution的静态字段 . 当然,这是硬件和操作系统问题 .

    表示定时器是否基于高分辨率性能计数器 .

  • 23

    如果您有兴趣了解性能,最好的答案是使用分析器 .

    否则,System.Diagnostics.StopWatch提供高分辨率计时器 .

  • 816

    StopWatch将使用高分辨率计数器

    秒表通过计算基础计时器机制中的计时器滴答来测量经过的时间 . 如果安装的硬件和操作系统支持高分辨率性能计数器,则Stopwatch类使用该计数器来测量经过的时间 . 否则,Stopwatch类使用系统计时器来测量经过的时间 . 使用Frequency和IsHighResolution字段确定秒表计时实施的精度和分辨率 .

    如果您正在测量IO,那么您的数据可能会受到外部事件的影响,我会非常担心 . 准确性(当你've indicated above). Instead I'd进行一系列测量并考虑这些数字的平均值和分布 .

相关问题