Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benchmarking method calls in C# [duplicate]

I'm looking for a way to benchmark method calls in C#.

I have coded a data structure for university assignment, and just came up with a way to optimize a bit, but in a way that would add a bit of overhead in all situations, while turning a O(n) call into O(1) in some.

Now I want to run both versions against the test data to see if it's worth implementing the optimization. I know that in Ruby, you could wrap the code in a Benchmark block and have it output the time needed to execute the block in console - is there something like that available for C#?

like image 283
Toms Mikoss Avatar asked Oct 25 '09 23:10

Toms Mikoss


People also ask

What is a benchmark in programming?

A benchmark is simply a test that is used to compare similar products. A computer benchmarking program works by running a series of well-defined tests on the PC to measure its performance.

How do you code a benchmark?

Steps for benchmarking code using BenchmarkDotNetAdd the necessary NuGet package. Add Benchmark attributes to your methods. Create a BenchmarkRunner instance. Run the application in Release mode.


1 Answers

Stolen (and modified) from Yuriy's answer:

private static void Benchmark(Action act, int iterations)
{
    GC.Collect();
    act.Invoke(); // run once outside of loop to avoid initialization costs
    Stopwatch sw = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        act.Invoke();
    }
    sw.Stop();
    Console.WriteLine((sw.ElapsedMilliseconds / iterations).ToString());
}

Often a particular method has to initialize some things, and you don't always want to include those initialization costs in your overall benchmark. Also, you want to divide the total execution time by the number of iterations, so that your estimate is more-or-less independent of the number of iterations.

like image 94
MusiGenesis Avatar answered Sep 21 '22 05:09

MusiGenesis