Skip to content

Instantly share code, notes, and snippets.

@VictorNicollet
Created September 16, 2020 19:43
Show Gist options
  • Save VictorNicollet/9e2eaab787946254e02dfbf553cf372e to your computer and use it in GitHub Desktop.
Save VictorNicollet/9e2eaab787946254e02dfbf553cf372e to your computer and use it in GitHub Desktop.
SIMD Benchmark: Span vs Array
using BenchmarkDotNet.Attributes;
using System;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
namespace SIMDBench
{
public class SumBench
{
public static float Sum(Span<float> a)
{
var av = MemoryMarshal.Cast<float, Vector<float>>(a);
var vSum = Vector<float>.Zero;
foreach (var v in av)
vSum += v;
var sum = Vector.Dot(vSum, Vector<float>.One);
a = a.Slice(av.Length * Vector<float>.Count);
foreach (var f in a)
sum += f;
return sum;
}
// From https://github.com/giladfrid009/SimpleSIMD/blob/master/SimpleSIMD/Reduction/Sum.cs
public static float Sum(float[] array)
{
Vector<float> vSum = Vector<float>.Zero;
float sum;
int vLen = Vector<float>.Count;
int i;
for (i = 0; i <= array.Length - vLen; i += vLen)
{
vSum += new Vector<float>(array, i);
}
sum = Vector.Dot(vSum, Vector<float>.One);
for (; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
public float[] Data;
[Params(10, 16, 100, 128, 1000, 1024, 60000, 65536)]
public int N;
[GlobalSetup]
public void GlobalSetup()
{
Data = Enumerable.Range(0, N).Select(i => (float)i).ToArray();
}
[Benchmark]
public float Span() => Sum(Data.AsSpan());
[Benchmark(Baseline = true)]
public float Array() => Sum(Data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment