通用函数来测试任何代表的性能 [英] Generic function to test the performance of any delegate
问题描述
在测试不同方法实现的相对性能时,我发现自己重写类似于这个的函数。
When testing the relative performance of different method implementations I find myself re-writing functions similar to this.
private static long Measure(
int iterations,
Func<string, string> func,
string someParameter)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < iterations; i++)
{
func(someParameter);
}
stopwatch.Stop();
return stopwatch.ElapsedTicks;
}
与其为我测试的每种方法singnature重写此函数,它会是可能编写一个通用的实现来测试任何delagate的性能?
Rather than rewriting this function for every method singnature that I test, would it be possible to write a generic implementation for performance testing any delagate? Something along the lines of
private static long Measure(
int iterations,
Delegate func,
params object[] parameters)
{
...
}
或
private static long Measure<TDelegate>(
int iterations,
TDelegate func,
params object[] parameters)
{
if (!typeof(TDelegate).IsSubclassOf(typeof(Delegate)))
{
throw new ArgumentException("Not a delegate", "func");
}
...
}
如果我能做到这一点,那么 编译
Expression< TDelegate> ;
在执行迭代之前?
If I can do this would it make sense to Compile
an Expression<TDelegate>
before performing the iterations?
推荐答案
为什么不使用Action,在lambda中设置参数。
Why not use an Action and you can set the parameters in a lambda.
private static long Measure(int iterations, Action action)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < iterations; i++)
{
action();
}
stopwatch.Stop();
return stopwatch.ElapsedTicks;
}
然后,您将它称为
$ b $ (100,()=> MyMethod(arg1,arg2,...)); b
Then you call it like
Measure(100, () => MyMethod(arg1,arg2,...));
这篇关于通用函数来测试任何代表的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!