Created
November 25, 2023 00:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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