Skip to content

Instantly share code, notes, and snippets.

@Alan-FGR
Created July 13, 2018 01:02
Show Gist options
  • Save Alan-FGR/72ae461d216678084ce9592a5fe5722d to your computer and use it in GitHub Desktop.
Save Alan-FGR/72ae461d216678084ce9592a5fe5722d to your computer and use it in GitHub Desktop.
Math Benchmark C#
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public struct Vec
{
public float x, y, z;
public Vec(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public override string ToString()
{
return $"{x:F2}, {y:F2}, {z:F2}";
}
}
public struct Mat
{
public float M11,M12,M13,M21,M22,M23,M31,M32,M33,M41,M42,M43;
public Mat(float s)
{
var r = new Random(42);
M11 = (float)r.NextDouble() * s; M12 = (float)r.NextDouble() * s; M13 = (float)r.NextDouble() * s;
M21 = (float)r.NextDouble() * s; M22 = (float)r.NextDouble() * s; M23 = (float)r.NextDouble() * s;
M31 = (float)r.NextDouble() * s; M32 = (float)r.NextDouble() * s; M33 = (float)r.NextDouble() * s;
M41 = (float)r.NextDouble() * s; M42 = (float)r.NextDouble() * s; M43 = (float)r.NextDouble() * s;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vec Transform(in Vec v)
{
return new Vec(
v.x * M11 + v.y * M21 + v.z * M31 + M41,
v.x * M12 + v.y * M22 + v.z * M32 + M42,
v.x * M13 + v.y * M23 + v.z * M33 + M43);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec operator * (Mat m, Vec v)
{
return new Vec(
v.x * m.M11 + v.y * m.M21 + v.z * m.M31 + m.M41,
v.x * m.M12 + v.y * m.M22 + v.z * m.M32 + m.M42,
v.x * m.M13 + v.y * m.M23 + v.z * m.M33 + m.M43);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec Transform(in Mat m, in Vec v)
{
return new Vec(
v.x * m.M11 + v.y * m.M21 + v.z * m.M31 + m.M41,
v.x * m.M12 + v.y * m.M22 + v.z * m.M32 + m.M42,
v.x * m.M13 + v.y * m.M23 + v.z * m.M33 + m.M43);
}
}
public static class MatExts
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec TransformExt(this Mat m, in Vec v)
{
return Mat.Transform(m, v);
}
}
public class Benchmarks
{
private static Mat m;
private static Vec v;
private const int QTY = 1<<8;
public static void Init()
{
m = new Mat(1);
v = new Vec(1.1f,1.2f,1.3f);
}
[Benchmark]
public Vec InVecRetVec()
{
for (int i = 0; i < QTY; i++)
v = m.Transform(v);
return v;
}
[Benchmark]
public Vec Static()
{
for (int i = 0; i < QTY; i++)
v = Mat.Transform(m, v);
return v;
}
[Benchmark]
public Vec Extension()
{
for (int i = 0; i < QTY; i++)
v = m.TransformExt(v);
return v;
}
[Benchmark]
public Vec Operator()
{
for (int i = 0; i < QTY; i++)
v = m * v;
return v;
}
}
class Program
{
static void Main(string[] args)
{
Benchmarks.Init();
BenchmarkRunner.Run<Benchmarks>();
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment