Skip to content

Instantly share code, notes, and snippets.

@EgorBo EgorBo/Benchmark.cs

Created Nov 1, 2019
Embed
What would you like to do?
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
static void Main(string[] args)
{
// I used .NET Core 3.1 + BDN 0.12.0
BenchmarkRunner.Run<Program>();
}
private static bool AlwaysFalseProp { get; } = SetupField();
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool SetupField()
{
return false;
}
[Benchmark(Baseline = true)]
public double Foo0()
{
return Math.Sqrt(42);
}
[Benchmark]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public double Foo1()
{
if (AlwaysFalseProp)
{
Console.WriteLine();
throw new Exception("unreachable");
}
return Math.Sqrt(42);
}
[Benchmark]
public double Foo2()
{
if (AlwaysFalseProp)
{
Console.WriteLine();
throw new Exception("unreachable");
}
return Math.Sqrt(42);
}
}
/*
| Method | Mean | Error | StdDev | Ratio | RatioSD |
|------- |----------:|----------:|----------:|-------:|--------:|
| Foo0 | 0.0103 ns | 0.0026 ns | 0.0023 ns | 1.00 | 0.00 |
| Foo1 | 1.0871 ns | 0.0014 ns | 0.0013 ns | 110.79 | 24.92 |
| Foo2 | 0.0230 ns | 0.0021 ns | 0.0017 ns | 2.49 | 0.61 |
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.