Does the Vector4 type actually improve performance? This benchmark is designed to test Vector4 and SIMD-optimized code against array-based code that uses for-loops.
#define VERSION1
using System;
using System.Diagnostics;
using System.Numerics;
class Program
{
public static void Main()
{
// For the array version.
var array0 = new int[]{ 10, 20, 30, 40 };
var array1 = new int[]{ 2, 3, 4, 5 };
var arrayResult = new int[4];
const int _max = 10000000;
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
#if VERSION1
// Version 1: uses vectors.
var v0 = new Vector4(10, 20, 30, 40);
var v1 = new Vector4(2, 3, 4, 5);
var result = v0 * v1;
result += new Vector4(1, 1, 1, 1);
var sum = result[0] + result[1] + result[2] + result[3];
if (sum != 404)
{
throw new Exception();
}
#endif
#if VERSION2
// Version 2: uses arrays.
Array.Clear(arrayResult);
for (int x = 0; x < array0.Length; x++)
{
arrayResult[x] = array0[x] * array1[x];
}
for (int x = 0; x < arrayResult.Length; x++)
{
arrayResult[x] += 1;
}
var sum = arrayResult[0] + arrayResult[1] + arrayResult[2] + arrayResult[3];
if (sum != 404)
{
throw new Exception();
}
#endif
}
s1.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
5.28 ns Vector4
16.33 ns int[], for