Don*_*nut 11
你可以使用这System.Diagnostics.Stopwatch门课.
Stopwatch sw = new Stopwatch();
sw.Start();
// Your method call here...
sw.Stop();
// Get the elapsed time
TimeSpan elapsed = sw.Elapsed;
Run Code Online (Sandbox Code Playgroud)
从这里,您可以使用TimeSpan.Ticks或TimeSpan.TotalSeconds属性分别确定经过的刻度或经过的秒数.
如果你愿意,你可以使用以下几行中的方法来围绕一个函数"包装"该功能,正如你所提到的(只是一个想法,你可能想调整这个代码以适合你的特定目的 - 传入参数等):
public static T ExecuteWithElapsedTime<T>(Func<T> function, out TimeSpan elapsedTime)
{
T rval;
Stopwatch sw = new Stopwatch();
sw.Start();
rval = function();
sw.Stop();
elapsedTime = sw.Elapsed;
return rval;
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样调用它(myFunc返回一个函数int):
TimeSpan elapsed;
int result = ExecuteWithElapsedTime(myFunc, out elapsed);
Run Code Online (Sandbox Code Playgroud)
可能更简单,但甚至不打扰这样的方法,只需将秒表代码与您的方法调用内联.