0

I made a small benchmarking library that takes in Func<Task> objects, runs them a certain number of times and uses a Stopwatch object to figure out the average time it took to run:

public static async Task<BenchmarkResults> BenchmarkAsync(Func<Task> action, int repetitions, bool singleCore)
{
    // Run func, time it each time, compute average, return results.
}

I have made a small IBenchmark interface with a single Run() method. The way I am currently using this library is making benchmark classes that implement IBenchmark and passing a lambda that calls the Run method to it. Those IBenchmark objects are added to DI via an extension method:

var results = AsyncBenchmarker.BenchmarkAsync(async () => await benchmark.Run(), attribute.Repetitions, false).Result;

I would like to move away from needing this IBenchmark interface in the first place, it is getting in my way more than anything at this point. What I would like to do instead of passing benchmark.Run() in my lambda is pass a reflective invocation of another method in that same class. I tried something like this:

AsyncBenchmarker.BenchmarkAsync(async () => 
    await benchmark.GetType().GetMethod("SomeOtherMethod").Invoke(benchmark, null), attribute.Repetitions, false).Wait();

The problem is that Invoke returns a nullable object and I need this to be awaitable. How can I achieve this?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Martin
  • 1,977
  • 5
  • 30
  • 67
  • 1
    Cast the result of your `Invoke` to `Task`? – GSerg Oct 28 '21 at 17:07
  • I changed the code to this : results = AsyncBenchmarker.BenchmarkAsync(async () => await (Task) type.GetMethods().Where(m => m.DeclaringType != typeof(object) && m.Name != "Run").FirstOrDefault() .Invoke(benchmark, null), attribute.Repetitions, false).Result; I did not know you could typecast something to a Task, thanks! There is however a small but measurable overhead from calling this reflectively (less than a millisecond). Any way around this? – Martin Oct 28 '21 at 17:14
  • 5
    Yes; don't do that. – GSerg Oct 28 '21 at 17:19
  • That's fair XD! I'll keep digging but at least I have this in my back pocket if all else fails. Cheers! – Martin Oct 28 '21 at 17:22

0 Answers0