我们如何在C#的BenchmarkDotNet中,在[Arguments]标签中传递动态参数?

3

我正在尝试对带有参数的方法进行基准测试。

[Benchmark]
public void ViewPlan(int x)
{
//code here
}

当我使用[Benchmark]注释执行代码时,我遇到了一个错误,提示“基准测试方法ViewPlan的签名不正确。该方法不应该有任何参数”。

因此,我尝试将[Arguments]注释添加到该方法中。

请参考链接:https://benchmarkdotnet.org/articles/samples/IntroArguments.html

[Benchmark]
[Arguments]
public void ViewPlan(int x)
{
//code here
}

在这个[Arguments]中,我们需要指定方法的参数值。然而,当功能被调用时,x的值是动态设置的。 有没有办法在[Arguments]中动态传递参数值呢? 同时,我们能否对静态方法进行基准测试?如果可以,如何操作?


你可以像这里所提到的那样使用ArgumentsSource,并且你可以在其中生成随机数。 - Eldar
@Eldar x的值可以是任何值。有一个包含1000条记录的网格。因此,x包含用户点击的行号。 - Vaishnavi Sabnawis
1个回答

6
我为您做了一个例子,请看看它是否符合您的需求。
public class IntroSetupCleanupIteration
{
        private int rowCount;
        private IEnumrable<object> innerSource;

        public IEnumerable<object> Source => this.innerSource; 

        [IterationSetup]
        public void IterationSetup()
        {
             // retrieve data or setup your grid row count for each iteration
             this.InitSource(42);
        }

        [GlobalSetup]
        public void GlobalSetup()
        {
             // retrieve data or setup your grid row count for every iteration
             this.InitSource(42);
        }

        [Benchmark]
        [ArgumentsSource(nameof(Source))]
        public void ViewPlan(int x)
        {
            // code here
        }

        private void InitSource(int rowCount)
        {
            this.innerSource = Enumerable.Range(0,rowCount).Select(t=> (object)t).ToArray(); // you can also shuffle it
        }
}

我不知道你如何设置你的数据。是每次迭代都设置一次,还是每个迭代只设置一次,因此我包含了这两种设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接