Created
September 16, 2020 19:43
-
-
Save VictorNicollet/9e2eaab787946254e02dfbf553cf372e to your computer and use it in GitHub Desktop.
SIMD Benchmark: Span vs Array
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 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