I was reading a question about c# code optimization and one solution was to use c++ with SSE. Is it possible to do SSE directly from a c# program?
Modern C# Supports SIMD/SSE instructions well and makes them fairly simple to use. Not all instructions are yet supported.
Here is an example of an SSE .Sum() of an array of uint[]:
using System.Numerics;
private static ulong SumSseInner(this uint[] arrayToSum, int l, int r)
{
var sumVectorLower = new Vector();
var sumVectorUpper = new Vector();
var longLower = new Vector();
var longUpper = new Vector();
int sseIndexEnd = l + ((r - l + 1) / Vector.Count) * Vector.Count;
int i;
for (i = l; i < sseIndexEnd; i += Vector.Count)
{
var inVector = new Vector(arrayToSum, i);
Vector.Widen(inVector, out longLower, out longUpper);
sumVectorLower += longLower;
sumVectorUpper += longUpper;
}
ulong overallSum = 0;
for (; i <= r; i++)
overallSum += arrayToSum[i];
sumVectorLower += sumVectorUpper;
for (i = 0; i < Vector.Count; i++)
overallSum += sumVectorLower[i];
return overallSum;
}
This particular function is part of an open source and free nuget package, HPCsharp, available on nuget.org, which I maintain.