Skip to content

Instantly share code, notes, and snippets.

@samoatesgames
Last active October 29, 2019 21:18
Show Gist options
  • Save samoatesgames/37128b2fdb0f9e874229e7d00b729b0e to your computer and use it in GitHub Desktop.
Save samoatesgames/37128b2fdb0f9e874229e7d00b729b0e to your computer and use it in GitHub Desktop.
Benchmarking different ways of reading multiple floats from a binary byte array
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.IO;
using System.Text;
namespace BinaryWriterBench
{
public class BinaryReaderBench
{
private readonly MemoryStream m_data = new MemoryStream();
public BinaryReaderBench()
{
using (var writer = new BinaryWriter(m_data, Encoding.UTF8, true))
{
writer.Write(1.0f);
writer.Write(2.0f);
writer.Write(3.0f);
writer.Write(4.0f);
}
}
[Benchmark(Baseline = true)]
public float[] Float4Using4Reads()
{
float[] output = new float[4];
m_data.Position = 0;
using (var reader = new BinaryReader(m_data, Encoding.UTF8, true))
{
output[0] = reader.ReadSingle();
output[1] = reader.ReadSingle();
output[2] = reader.ReadSingle();
output[3] = reader.ReadSingle();
}
return output;
}
[Benchmark]
public float[] Float4UsingSingleRead()
{
float[] output = new float[4];
m_data.Position = 0;
using (var reader = new BinaryReader(m_data, Encoding.UTF8, true))
{
var temp = reader.ReadBytes(16);
output[0] = BitConverter.ToSingle(temp, 0);
output[1] = BitConverter.ToSingle(temp, 4);
output[2] = BitConverter.ToSingle(temp, 8);
output[3] = BitConverter.ToSingle(temp, 12);
}
return output;
}
[Benchmark]
public float[] Float4UsingBlockCopy()
{
float[] output = new float[4];
m_data.Position = 0;
using (var reader = new BinaryReader(m_data, Encoding.UTF8, true))
{
var temp = reader.ReadBytes(16);
Buffer.BlockCopy(temp, 0, output, 0, 16);
}
return output;
}
[Benchmark]
public float[] Float4UsingMemoryCopy()
{
float[] output = new float[4];
m_data.Position = 0;
using (var reader = new BinaryReader(m_data, Encoding.UTF8, true))
{
var temp = reader.ReadBytes(16);
unsafe
{
fixed (float* pinnedDestination = output)
{
fixed (byte* pinnedSource = temp)
{
Buffer.MemoryCopy(pinnedSource, pinnedDestination, 16, 16);
}
}
}
}
return output;
}
}
public class Program
{
public static void Main(string[] args)
{
#if DEBUG
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, new DebugInProcessConfig());
#endif
var summary = BenchmarkRunner.Run<BinaryReaderBench>();
Console.ReadLine();
}
}
}
@samoatesgames
Copy link
Author

Method Mean Error StdDev Ratio RatioSD
Float4Using4Reads 136.0 ns 2.82 ns 4.22 ns 1.00 0.00
Float4UsingSingleRead 114.5 ns 1.37 ns 1.28 ns 0.84 0.03
Float4UsingBlockCopy 105.1 ns 0.88 ns 0.82 ns 0.77 0.03
Float4UsingMemoryCopy 100.2 ns 0.50 ns 0.44 ns 0.73 0.03

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment