我已经测试了联锁和其他一些替代方案。结果如下
ForSum: 16145,47 ticks
ForeachSum: 17702,01 ticks
ForEachSum: 66530,06 ticks
ParallelInterlockedForEachSum: 484235,95 ticks
ParallelLockingForeachSum: 965239,91 ticks
LinqSum: 97682,97 ticks
ParallelLinqSum: 23436,28 ticks
ManualParallelSum: 5959,83 ticks
所以 interlocked 比非并行 linq 慢 5 倍,比 parallelLinq 慢 20 倍。它与“缓慢而丑陋的 linq”相比。手动方法比它快几个数量级,我认为比较它们没有意义。这怎么可能?如果是真的,为什么我应该使用这个类而不是手动/Linq 并行求和?特别是如果使用 Linq 的目的是我可以做所有事情而不是互锁,有大量的方法。
所以基准代码在这里:
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace InterlockedTest
{
internal static class Program
{
private static void Main()
{
DoBenchmark();
Console.ReadKey();
}
private static void DoBenchmark()
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
DisableGC();
var arr = Enumerable.Repeat(6, 1005000*6).ToArray();
int correctAnswer = 6*arr.Length;
var methods = new Func<int[], int>[]
{
ForSum, ForeachSum, ForEachSum, ParallelInterlockedForEachSum, ParallelLockingForeachSum,
LinqSum, ParallelLinqSum, ManualParallelSum
};
foreach (var method in methods)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var result = new long[100];
for (int i = 0; i < result.Length; ++i)
{
result[i] = TestMethod(method, arr, correctAnswer);
}
Console.WriteLine("{0}: {1} ticks", method.GetMethodInfo().Name, result.Average());
}
}
private static void DisableGC()
{
GCLatencyMode oldMode = GCSettings.LatencyMode;
// Make sure we can always go to the catch block,
// so we can set the latency mode back to `oldMode`
RuntimeHelpers.PrepareConstrainedRegions();
GCSettings.LatencyMode = GCLatencyMode.LowLatency;
}
private static long TestMethod(Func<int[], int> foo, int[] arr, int correctAnswer)
{
var watch = Stopwatch.StartNew();
if (foo(arr) != correctAnswer)
{
return -1;
}
watch.Stop();
return watch.ElapsedTicks;
}
private static int ForSum(int[] arr)
{
int res = 0;
for (int i = 0; i < arr.Length; ++i)
{
res += arr[i];
}
return res;
}
private static int ForeachSum(int[] arr)
{
int res = 0;
foreach (var x in arr)
{
res += x;
}
return res;
}
private static int ForEachSum(int[] arr)
{
int res = 0;
Array.ForEach(arr, x => res += x);
return res;
}
private static int ParallelInterlockedForEachSum(int[] arr)
{
int res = 0;
Parallel.ForEach(arr, x => Interlocked.Add(ref res, x));
return res;
}
private static int ParallelLockingForeachSum(int[] arr)
{
int res = 0;
object syncroot = new object();
Parallel.ForEach(arr, i =>
{
lock (syncroot)
{
res += i;
}
});
return res;
}
private static int LinqSum(int[] arr)
{
return arr.Sum();
}
private static int ParallelLinqSum(int[] arr)
{
return arr.AsParallel().Sum();
}
static int ManualParallelSum(int[] arr)
{
int blockSize = arr.Length / Environment.ProcessorCount;
int blockCount = arr.Length / blockSize + arr.Length % blockSize;
var wHandlers = new ManualResetEvent[blockCount];
int[] tempResults = new int[blockCount];
for (int i = 0; i < blockCount; i++)
{
ManualResetEvent handler = (wHandlers[i] = new ManualResetEvent(false));
ThreadPool.UnsafeQueueUserWorkItem(param =>
{
int subResult = 0;
int blockIndex = (int)param;
int endBlock = Math.Min(arr.Length, blockSize * blockIndex + blockSize);
for (int j = blockIndex * blockSize; j < endBlock; j++)
{
subResult += arr[j];
}
tempResults[blockIndex] = subResult;
handler.Set();
}, i);
}
int res = 0;
for (int block = 0; block < blockCount; ++block)
{
wHandlers[block].WaitOne();
res += tempResults[block];
}
return res;
}
}
}