思路:将要执行的方法委托给测量类执行,返回测量时间和目标方法的返回值。
测量类:
public class TestTime
{
/// <summary>
/// 获取方法运行耗时
/// </summary>
/// <param name="_method">委托方法</param>
/// <param name="return_Obj">执行委托方法后的返回值</param>
/// <param name="_params">变长参数</param>
/// <returns>该方法返回测量的毫秒值</returns>
public static Double getMethodRuntime(Delegate _method, out Object return_Obj, params Object[] _params)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
//执行委托
if (_params.Length == 0)
{
//开始测量
stopwatch.Start();
//动态调用
return_Obj = _method.DynamicInvoke();
//结束测量
stopwatch.Stop();
}
else {
//开始测量
stopwatch.Start();
return_Obj = _method.DynamicInvoke(_params);
//结束测量
stopwatch.Stop();
}
//此字段不严谨
//return stopwatch.ElapsedMilliseconds;
TimeSpan timeSpan = stopwatch.Elapsed;
//获取毫秒值
return timeSpan.TotalMilliseconds;
}
}
测试类:
class Program
{
//委托
public delegate String _delegate();
public static _delegate _Method = One;
static void Main(string[] args)
{
Double millisecond = TestTime.getMethodRuntime(_Method, out Object obj);
Console.WriteLine(millisecond);
Console.ReadKey();
}
static String One()
{
Console.WriteLine("--------------One方法-------------");
for (int i = 0; i < 50; i++)
{
System.Threading.Thread.Sleep(10);
}
return "One方法";
}
}