代码之家  ›  专栏  ›  技术社区  ›  Matthew Watson

Plinq给出了与Linq不同的结果——我做错了什么?

  •  6
  • Matthew Watson  · 技术社区  · 17 年前

    林克骨料=75.8310477905274(正确)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main()
            {
                double[] array = new double[100];
    
                for (int i = 0; i < array.Length; ++i)
                {
                    array[i] = i;
                }
    
                double sum1 = array.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
                Console.WriteLine("Linq aggregate = " + sum1);
    
                IParallelEnumerable<double> parray = array.AsParallel<double>();
                double sum2 = parray.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
                Console.WriteLine("Plinq aggregate = " + sum2);
            }
        }
    }
    
    2 回复  |  直到 17 年前
        1
  •  3
  •   Community Mohan Dere    5 年前

    MSDN Blogs:

    而不是期望一个值

    public static double Average(this IEnumerable<int> source)
    {
        return source.AsParallel().Aggregate(
            () => new double[2],
            (acc, elem) => { acc[0] += elem; acc[1]++; return acc; },
            (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
            acc => acc[0] / acc[1]);
    }
    

    线。现在每个线程都得到了它的 函数与累加器组合 函数可以自由更改 蓄电池。PLINQ保证 蓄能器将无法访问

    因此,在您的情况下,您还需要传递一个累加器函数,该函数对并行聚合的输出求和(因此您看到的结果大约是它应该的一半)。

        2
  •  0
  •   Matthew Watson    17 年前

    using System;
    using System.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main()
            {
                Test();
            }
    
            static void Test()
            {
                double[] array = new double[100];
    
                for (int i = 0; i < array.Length; ++i)
                {
                    array[i] = i;
                }
    
                double sum1 = array.Aggregate((total, current) => total + Math.Sqrt(Math.Abs(Math.Sin(current))));
                Console.WriteLine("Linq aggregate = " + sum1);
    
                IParallelEnumerable<double> parray = array.AsParallel();
    
                double sum2 = parray.Aggregate
                (
                    0.0,
                    (total1, current1) => total1 + Math.Sqrt(Math.Abs(Math.Sin(current1))),
                    (total2, current2) => total2 + current2,
                    acc => acc
                );
    
                Console.WriteLine("Plinq aggregate = " + sum2);
            }
        }
    }