为什么联锁如此缓慢

本文关键字:缓慢 为什么 | 更新日期: 2023-09-27 18:28:33

我测试了一个互锁和其他一些替代方案。结果低于

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

如此互锁的速度是甚至非平行linq的5倍并且是平行linq慢20倍。它被比作"又慢又丑的linq"。手动方法比它快几个数量级,我认为将它们进行比较毫无意义。这怎么可能?如果这是真的,为什么我应该使用这个类而不是手动/Linq并行求和?特别是如果使用Linq i的目的是可以做任何事情,而不是互锁,方法数量少得可怜。

所以测试台代码在这里:

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;
        }
    }
}

为什么联锁如此缓慢

这里的问题是,它必须对每一个添加进行同步,这是一个巨大的开销。

Microsoft提供了一个Partitioner类,它主要用于提供您在ManualParallelSum()中使用的一些逻辑。

如果使用Partitioner,它会大大简化代码,并且运行时间大致相同。

这里有一个示例实现——如果您将其添加到测试程序中,您应该会看到类似于ManualParallelSum():的结果

private static int PartitionSum(int[] numbers)
{
    int result = 0;
    var rangePartitioner = Partitioner.Create(0, numbers.Length);
    Parallel.ForEach(rangePartitioner, (range, loopState) =>
    {
        int subtotal = 0;
        for (int i = range.Item1; i < range.Item2; i++)
            subtotal += numbers[i];
        Interlocked.Add(ref result, subtotal);
    });
    return result;
}

当没有争用发生时,互锁和锁定是快速操作
在示例中,有很多争用,开销变得比底层操作(这是一个非常小的操作)重要得多。

即使没有并行性,Interlocked.Add也会增加少量开销,但不会增加太多。

private static int InterlockedSum(int[] arr)
{
    int res = 0;
    for (int i = 0; i < arr.Length; ++i)
    {
        Interlocked.Add(ref res, arr[i]);
    }
    return res;
}

结果是:ForSum:6682.45 ticks
InterlockedSum:15309.63 ticks

与手动实现的比较看起来不公平,因为您知道操作的性质,所以将操作分为块。其他实现不能假设这一点。