C# 普通代码实现:
public static int GetXORSum(int[] arr1, int[] arr2)
{
int tot1 = arr1.Aggregate(0, (a, b) => a ^ b);
int tot2 = arr2.Aggregate(0, (a, b) => a ^ b);
return tot1 & tot2;
}
C# 向量方法实现:
public static int GetXORSum(int[] arr1, int[] arr2)
{
int tot1 = GetXor(arr1);
int tot2 = GetXor(arr2);
return tot1 & tot2;
}
private static int GetXor(int[] array)
{
int vectorSize = Vector256<int>.Count;
int res = 0;
fixed (int* ptr = array)
{
Vector256<int> mask = *(Vector256<int>*)(ptr);
for (int i = vectorSize; i < array.Length; i += vectorSize)
{
mask = Avx2.Xor(mask, *(Vector256<int>*)(ptr + i));
}
int* maskPtr = (int*)&mask;
for (int j = 0; j < vectorSize; j++)
{
res ^= *(maskPtr + j);
}
}
return res;
}
Release环境下效率比较: