2

首先,我在双核 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);
    }
  }
}
4

2 回答 2

4

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

于 2010-04-10T23:44:38.573 回答
0

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

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

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

于 2010-04-10T23:50:53.813 回答