Using SSE in c# is it possible?

后端 未结 10 1939
借酒劲吻你
借酒劲吻你 2020-11-29 11:02

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?

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 11:42

    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.

提交回复
热议问题