我正在尝试提出一种方法来测量并返回另一种方法的执行时间。基本上是这样的:
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.
我该怎么做(MeasureExecTime方法)?
答案 0 :(得分:7)
public static TimeSpan MeasureExecTime(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
return stopwatch.Elapsed;
}
答案 1 :(得分:6)
我刚刚创建了一种方法来测试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 :(得分:1)
有关此主题的详细讨论,请参阅此主题,接受的答案有很多缺陷。
Benchmarking small code samples in C#, can this implementation be improved?
答案 3 :(得分:0)