Skip to content

Instantly share code, notes, and snippets.

@BenMakesGames
Created November 25, 2023 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMakesGames/441fc0bf25205dbd9960c43a8a10f007 to your computer and use it in GitHub Desktop.
Save BenMakesGames/441fc0bf25205dbd9960c43a8a10f007 to your computer and use it in GitHub Desktop.
A simple Program.cs for selecting and running any of your BenchmarkDotNet benchmarks.
using System.Reflection;
using BenchmarkDotNet.Running;
// put all the benchmark classes into their own namespace, for easier discoverability. if you don't like this,
// change the next few lines to find your benchmarks using whatever logic you prefer.
const string BenchmarksNamespace = "YourBenchmarkNamespaceHere.Benchmarks";
var allBenchmarks = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t is { Namespace: BenchmarksNamespace, IsClass: true })
.ToList();
// the meat & potatoes:
if (SelectBenchmark(allBenchmarks) is { } benchmark)
{
Console.WriteLine();
BenchmarkRunner.Run(benchmark);
}
return;
Type? SelectBenchmark(List<Type> benchmarks)
{
var selected = 0;
Console.CursorVisible = false;
string Label(int i) => i < benchmarks.Count ? benchmarks[i].Name : "Cancel";
while (true)
{
Console.Clear();
Console.WriteLine("Select a benchmark to run");
for (var i = 0; i < benchmarks.Count + 1; i++)
{
if (i == selected)
{
var oldForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"> {Label(i)}");
Console.ForegroundColor = oldForegroundColor;
}
else
Console.WriteLine($" {Label(i)}");
}
switch (Console.ReadKey().Key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.NumPad8:
selected = selected > 0 ? selected - 1 : benchmarks.Count;
break;
case ConsoleKey.DownArrow:
case ConsoleKey.NumPad2:
selected = (selected + 1) % (benchmarks.Count + 1);
break;
case ConsoleKey.Enter:
Console.CursorVisible = true;
return selected < benchmarks.Count ? benchmarks[selected] : null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment