From d54e2504a0a7d6d16fa8c60e2805a2e961187b65 Mon Sep 17 00:00:00 2001 From: Timothy Schenk Date: Thu, 10 Aug 2023 22:07:40 +0200 Subject: [PATCH] feat: add basic benchmark for binary parsing --- Benchmarks/Benchmarks.csproj | 15 +++++++ Benchmarks/BinaryConversionBenchmarks.cs | 50 ++++++++++++++++++++++++ Benchmarks/Program.cs | 12 ++++++ 3 files changed, 77 insertions(+) create mode 100644 Benchmarks/Benchmarks.csproj create mode 100644 Benchmarks/BinaryConversionBenchmarks.cs create mode 100644 Benchmarks/Program.cs diff --git a/Benchmarks/Benchmarks.csproj b/Benchmarks/Benchmarks.csproj new file mode 100644 index 0000000..3d08c42 --- /dev/null +++ b/Benchmarks/Benchmarks.csproj @@ -0,0 +1,15 @@ + + + + Exe + enable + enable + default + net7.0 + + + + + + + diff --git a/Benchmarks/BinaryConversionBenchmarks.cs b/Benchmarks/BinaryConversionBenchmarks.cs new file mode 100644 index 0000000..ee9961d --- /dev/null +++ b/Benchmarks/BinaryConversionBenchmarks.cs @@ -0,0 +1,50 @@ +using System.Security.Cryptography; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Order; + +namespace Benchmarks; + +[SimpleJob(RuntimeMoniker.NativeAot70)] +[SimpleJob(RuntimeMoniker.Net70)] +[SimpleJob(RuntimeMoniker.Net60)] +[Orderer(SummaryOrderPolicy.FastestToSlowest)] +[RankColumn] +[MemoryDiagnoser] +[ExceptionDiagnoser] +[ThreadingDiagnoser] +[DisassemblyDiagnoser] +public class BinaryConversionBenchmarks +{ + private byte[] data; + private int offset; + + [GlobalSetup] + public void Setup() + { + data = RandomNumberGenerator.GetBytes(4000); + offset = RandomNumberGenerator.GetInt32(0, 3500); + } + + [Benchmark] + public Int16 BitConverterTest() + { + return BitConverter.ToInt16(data, offset); + } + + [Benchmark] + public Int16 BinaryReader() + { + using MemoryStream ms = new MemoryStream(data); + using BinaryReader reader = new BinaryReader(ms); + reader.BaseStream.Position = offset; + return reader.ReadInt16(); + } + + [Benchmark] + public Int16 BinaryPrimitives() + { + return System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian( + new ArraySegment(data, offset, sizeof(short))); + } +} \ No newline at end of file diff --git a/Benchmarks/Program.cs b/Benchmarks/Program.cs new file mode 100644 index 0000000..2e87545 --- /dev/null +++ b/Benchmarks/Program.cs @@ -0,0 +1,12 @@ +using System.Reflection; +using BenchmarkDotNet.Running; + +namespace Benchmarks; + +internal class Program +{ + public static void Main(string[] args) + { + BenchmarkRunner.Run(Assembly.GetExecutingAssembly()); + } +} \ No newline at end of file