【问题标题】:TPL doesn’t appear to improve execution speed in MSDN example在 MSDN 示例中,TPL 似乎没有提高执行速度
【发布时间】:2013-06-26 09:06:06
【问题描述】:

当我使用the example from MSDN时:

var queryA = from num in numberList.AsParallel()
             select ExpensiveFunction(num); //good for PLINQ

var queryB = from num in numberList.AsParallel()
             where num % 2 > 0
             select num; //not as good for PLINQ

我的示例程序:

static void Main(string[] args)
{
   // ThreadPool.SetMinThreads(100, 100);

        var numberList = new List<int>();
        for (int i = 0; i <= 1000; i++)
        {
            numberList.Add(i);
        }
        Stopwatch sw = new Stopwatch();
        sw.Start();
        var queryA = from num in numberList
                     select ExpensiveFunction(num); //good for PLINQ
        var c = queryA.ToList<int>();
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds);
        sw.Reset();
        sw.Start();
        var queryB = from num in numberList.AsParallel()
                     select ExpensiveFunction(num); //good for PLINQ
        c = queryB.ToList<int>();
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds);
        Console.ReadKey();
}

static int ExpensiveFunction(int a)
{
    a = a + 100 - 9 + 0 + 98;
    // Console.WriteLine(a);
    return a;
}

结果是:

7
41

为什么使用AsParallel() 比不使用慢?

【问题讨论】:

  • a += 189; 的计算成本

标签: c# multithreading task-parallel-library threadpool


【解决方案1】:

您的ExpensiveFunction 对于计算机来说确实不是一个昂贵的功能。

可以非常快速地完成简单的数学运算。

也许试试Thread.Sleep(500);。这将告诉 CPU 暂停半秒,这将模拟实际昂贵函数的效果。

编辑——我应该说,它变慢的原因是因为并行处理涉及的开销比实际计算的工作量要多。 See this answer for a better explanation.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多