capypad
0 day streak
csharp / expert
Snippet

SIMD Vectorization with Vector<T>

Single Instruction, Multiple Data (SIMD) allows a single CPU instruction to process multiple data points simultaneously. Vector<T> in C# enables hardware-accelerated parallel processing on arrays, significantly boosting performance for mathematical and data-heavy algorithms.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
public void VectorAdd(int[] a, int[] b, int[] result) {
int vSize = Vector<int>.Count;
for (int i = 0; i <= a.Length - vSize; i += vSize) {
var v1 = new Vector<int>(a, i);
var v2 = new Vector<int>(b, i);
(v1 + v2).CopyTo(result, i);
}
}
Breakdown
1
int vSize = Vector<int>.Count;
Retrieves the number of elements the hardware can process in one register (e.g., 4 or 8).
2
(v1 + v2).CopyTo(result, i);
Performs addition on all vector elements at once and writes them back to memory.