3

I am trying to benchmark a method with parameters.

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

While executing the code with [Benchmark] annotation, I got an error as "Benchmark method ViewPlan has incorrect signature. Method shouldn't have any arguments". So I tried to add [Arguments] annotation to the method as well. Refer link: https://benchmarkdotnet.org/articles/samples/IntroArguments.html

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

In this [Arguments] we need to specify the value of the parameter for the method as well. However, value of x is set dynamically when the functionality is called. Is there any way to pass the parameter value dynamically in [Arguments] ? Also can we benchmark static methods?If yes then how?

theduck
  • 2,589
  • 13
  • 17
  • 23
  • You can use `ArgumentsSource` as mentioned [here](https://benchmarkdotnet.org/articles/features/parameterization.html) and you can generate random numbers in there. – Eldar Nov 21 '19 at 10:46
  • @Eldar the value of x can be anything. There is a grid which has for eg 1000 records. So x contains the rownumber on which user has clicked. – Vaishnavi Sabnawis Nov 21 '19 at 12:38

1 Answers1

6

I have made an example for you. See if it fits your needs.

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

I don't know how you set up your data. For each iteration or once for every iteration so i include both setups.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eldar
  • 9,781
  • 2
  • 10
  • 35