Generic function to test the performance of any de

2019-02-26 21:01发布

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;
}

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)
{
    ...
}

or

    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");
    }

    ...
}

If I can do this would it make sense to Compile an Expression<TDelegate> before performing the iterations?

2条回答
迷人小祖宗
2楼-- · 2019-02-26 22:03

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;
}

Then you call it like

Measure(100, () => MyMethod(arg1,arg2,...));
查看更多
闹够了就滚
3楼-- · 2019-02-26 22:04

You can just use an anonymous function to pass the parameters:

var p1 = ..
var p2 = ..
var p3 = ..
var p4 = ..
var p5 = ..
Measure(1000, (x) => MyTestFunc(p1, p2, p3, p4, p5), str);
查看更多
登录 后发表回答