【问题标题】:Why is PLINQ slower than LINQ for this code?为什么此代码的 PLINQ 比 LINQ 慢?
【发布时间】:2010-04-10 23:29:46
【问题描述】:

首先,我在双核 2.66Ghz 处理器机器上运行它。我不确定我是否在正确的位置调用了 .AsParallel() 。我也直接在范围变量上尝试过,但速度仍然较慢。我不明白为什么...

这是我的结果:

进程非并行 1000 耗时 146 毫秒

进程并行 1000 耗时 156 毫秒

进程非并行 5000 耗时 5187 毫秒

进程并行 5000 耗时 5300 毫秒

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace DemoConsoleApp
{
  internal class Program
  {
    private static void Main()
    {
      ReportOnTimedProcess(
        () => GetIntegerCombinations(),
        "non-parallel 1000");

      ReportOnTimedProcess(
        () => GetIntegerCombinations(runAsParallel: true),
        "parallel 1000");

      ReportOnTimedProcess(
        () => GetIntegerCombinations(5000),
        "non-parallel 5000");

      ReportOnTimedProcess(
        () => GetIntegerCombinations(5000, true),
        "parallel 5000");

      Console.Read();
    }

    private static List<Tuple<int, int>> GetIntegerCombinations(
      int iterationCount = 1000, bool runAsParallel = false)
    {
      IEnumerable<int> range = Enumerable.Range(1, iterationCount);

      IEnumerable<Tuple<int, int>> integerCombinations =
        from x in range
        from y in range
        select new Tuple<int, int>(x, y);

      return runAsParallel
               ? integerCombinations.AsParallel().ToList()
               : integerCombinations.ToList();
    }

    private static void ReportOnTimedProcess(
      Action process, string processName)
    {
      var stopwatch = new Stopwatch();
      stopwatch.Start();
      process();
      stopwatch.Stop();

      Console.WriteLine("Process {0} took {1} milliseconds",
                        processName, stopwatch.ElapsedMilliseconds);
    }
  }
}

【问题讨论】:

    标签: .net-4.0 parallel-processing plinq


    【解决方案1】:

    它会稍微慢一些,因为 PLINQ 有一定的开销(线程、调度等),所以您必须仔细选择要并行化的内容。您要进行基准测试的这个特定代码实际上并不值得并行化,您必须对负载很大的任务进行并行化,否则开销将超过并行化的好处。

    【讨论】:

      【解决方案2】:

      您在此处的大部分执行时间很可能是通过ToList() 方法实际创建列表。这将不得不执行多次内存分配、调整列表大小等。您也不会从此处的并行化中获得太多好处,因为最终操作必须同步(您正在输出上构建单个列表)。

      尝试在并行部分中做一些更复杂/更昂贵的事情,例如素数分解,并将迭代次数增加到数十万(5000 是一个非常在分析时使用的小数字) .你应该开始看到不同之处了。

      还要确保您在发布模式下进行分析;我经常看到有人尝试在调试模式下进行分析,但结果并不准确。

      【讨论】:

      • 当迭代计数设置为 5000 (5000*5000) 时,我的示例中的代码实际上会创建 2500 万个元组组合 我认为我认为问题在于每个逻辑迭代都太小而无法并行化无论如何。谢谢!
      猜你喜欢
      • 2019-03-04
      • 2011-03-14
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多