代码之家  ›  专栏  ›  技术社区  ›  Alex

生成一个方法以返回另一个方法的执行时间

  •  2
  • Alex  · 技术社区  · 16 年前

    我正试图想出一个方法来度量并返回另一个方法的执行时间。基本上是这样的:

    public void DoSomething(Int32 aNumber)
    { /* Stuff happens */ }
    
    //
    // Somewhere else in code:
    TimeSpan executionTime = MyDiag.MeasureExecTime(DoSomething(5));
    
    // Now executionTime contains how long DoSomething(5) took to execute,
    // e.g. 2.55463 seconds.
    

    我该怎么做(MeasureExactime方法)?

    4 回复  |  直到 13 年前
        1
  •  6
  •   Community CDub    8 年前

    我刚刚创建了一个这样的方法来测试 this SO question :

    private static TimeSpan MeasureExecTime(Action action, int iterations)
    {
        action(); // warm up
        var sw = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        return sw.Elapsed;
    }
    

    用法:

    MeasureExecTime(() => DoSomething(5), 100000);
    

    280Z28 如果不想测试多个迭代,请给出答案:-)

        2
  •  7
  •   Sam Harwell    16 年前
    public static TimeSpan MeasureExecTime(Action action)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        action();
        return stopwatch.Elapsed;
    }
    
        3
  •  1
  •   Sam Saffron    8 年前

    关于这个话题,请看这条线索进行长时间的讨论,公认的答案有不少缺陷。

    Benchmarking small code samples in C#, can this implementation be improved?