假设我正在对许多不同的函数进行基准测试,而我只想调用一个函数来运行foo n次。
当所有函数具有相同的返回类型时,您可以执行
static void benchmark(Func<ReturnType> function, int iterations)
{
Console.WriteLine("Running {0} {1} times.", function.Method.Name, iterations);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < iterations; ++i)
{
function();
}
stopwatch.Stop();
Console.WriteLine("Took {0} to run {1} {2} times.", stopwatch.Elapsed, function.Method.Name, iterations);
}
但是,如果我要测试的函数具有不同的返回类型怎么办?我可以接受泛型类型的函数吗?我尝试使用,Func <T>
但不起作用。
您当然可以使其通用:
static void Benchmark<T>(Func<T> function, int iterations)
您可能还需要重载它来接受Action
,对void
方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句