为什么互锁是如此缓慢

时间:2013-08-22 11:33:44

标签: c# .net linq parallel-processing parallel.foreach

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

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

因此,与parallelLinq相比,互锁的速度比非平行的linq慢5倍,慢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;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

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

Microsoft拥有provided a Partitioner class,其基本上旨在提供您在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;
}

答案 1 :(得分:0)

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

即使没有并行性,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蜱 InterlockedSum:15309.63 ticks

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