BenchmarkDotNet With Params and Arguments!.

BenchmarkDotNet With Params and Arguments!.

I just have had to run a few benchmarks on a piece of code and realize the benchmark did not work as expected.

I needed to run Benchmark on functions where those need params or arguments to be executed, so, let's move with an example:

If you have no idea how to run a benchmark, here you have a previous article about: https://www.dhirubhai.net/pulse/did-you-use-parallelfor-what-benchmarks-lets-talk-leonardo-sasso-hhwuf/?trackingId=2abQ30OvTj2DsIA0wL4HWw%3D%3D

My original code was:

[Benchmark]
public static double MyPow(double x, int n)
    {
        return Math.Pow(x, n);
    }        

Of course, the benchmark did not run and it is obvious, how the Benchmark will know what arguments are sent to this feature?.

Well to answer the question, the library uses attributes to specify a lot of things that can be useful, however in this case, we are going to use just the [Arguments] and the Params one.

So, analyzing the MyPow funct, this one is expecting two params (x and n), so we will use the [Arguments(2,5)] to let the benchmark know, x will be 2 and n will be 5.

        [Benchmark]
        [Arguments(2,5)]
        public static double MyPow(double x, int n)
        {
            return Math.Pow(x, n);
        }        

Now, ladies and gentlemen, we are ready to run the benchmarks!

要查看或添加评论,请登录

Leonardo S.的更多文章

社区洞察

其他会员也浏览了