1y ago · Aug 30, 2024 11:30 AM
Did you know .NET has cross-platform SIMD vectorization built right into the standard library? automatically uses whatever vector width the host CPU supports (128-bit SSE, 256-bit AVX2, or 512-bit AVX-512)!
Vectorized Array Multiplication (Processing 8 or 16 floats per cycle):
Benchmark: **7.5x faster** than a standard for-loop on an Intel 13th Gen CPU!
CODE
Vector<T>Vectorized Array Multiplication (Processing 8 or 16 floats per cycle):
CSHARP
using System.Numerics;
public static class SimdMath
{
public static void MultiplyArrays(float[] a, float[] b, float[] result)
{
int simdLength = Vector<float>.Count; // e.g. 8 on AVX2
int i = 0;
// Process SIMD chunks in parallel
for (; i <= a.Length - simdLength; i += simdLength)
{
var va = new Vector<float>(a, i);
var vb = new Vector<float>(b, i);
(va * vb).CopyTo(result, i); // Executes in 1 CPU instruction!
}
// Clean up remaining tail elements
for (; i < a.Length; i++)
{
result[i] = a[i] * b[i];
}
}
}Benchmark: **7.5x faster** than a standard for-loop on an Intel 13th Gen CPU!
SimdSamurai · AVX-512 & SSE
Vectorizing matrix multiplications and particle engines with...
Vectorizing matrix multiplications and particle engines with...
The following users thanked SimdSamurai for this post: