c# - 在 C# 中,顺序循环如何比并行循环运行得更快?

标签 c# task-parallel-library

我尝试了一个非常简单的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace TPLExample {
    class Program {
        static void Main(string[] args) {
            int[] dataItems = new int[100];
            double[] resultItems = new double[100];

            for (int i = 0; i < dataItems.Length; ++i) {
                dataItems[i] = i;
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Reset();
            stopwatch.Start();
            Parallel.For(0, dataItems.Length, (index) => {
                resultItems[index] = Math.Pow(dataItems[index], 2);
            });
            stopwatch.Stop();
            Console.WriteLine("TPL Time elapsed: {0}", stopwatch.Elapsed);

            stopwatch.Reset();
            stopwatch.Start();
            for (int i = 0; i < dataItems.Length; ++i) {
                resultItems[i] = Math.Pow(dataItems[i], 2);
            }
            stopwatch.Stop();
            Console.WriteLine("Sequential Time elapsed: {0}", stopwatch.Elapsed);

            WaitForEnterKey();
        }

        public static void WaitForEnterKey() {
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }

        public static void PrintMessage() {
            Console.WriteLine("Message printed");
        }
    }
}

输出是:

TPL Time elapsed: 00:00:00.0010670
Sequential Time elapsed: 00:00:00.0000178
Press enter to finish

顺序循环比 TPL 快得多!这怎么可能?据我了解,Parallel.For 中的计算将并行执行,所以它必须更快吗?

最佳答案

简单地说:为了仅迭代一百多个项目并执行一个小的数学运算,生成新线程并等待它们完成会产生比仅通过循环运行更多的开销。

From my understanding, calculation within the Parallel.For will be executed in parallel, so must it be faster?

当人们对计算机性能做出笼统的陈述时通常会发生这种情况,这里有更多的变数在起作用,您不能真正做出这样的假设。例如,在您的 for 循环中,您所做的只是 Math.Pow,处理器可以非常快速地执行它。如果这是一个 I/O 密集型操作,需要每个线程等待很长时间,或者即使它是一系列处理器密集型操作,您也会从并行处理中获得更多 yield (假设您有一个多线程处理器) .但事实上,创建和同步这些线程的开销远远大于并行性可能给您带来的任何优势。

关于c# - 在 C# 中,顺序循环如何比并行循环运行得更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763184/

相关文章:

c# - ListView 上的水平滚动

c# - 如何将 XmlCDataSection 转换为 XDocument

c# - 在 foreach 中使用 Session 变量

c# - 将 ICollection<T> 转换为 List<T>

c# - 限制通过并行任务库运行的事件任务数量的最佳方法

c# - 如何暂停和继续 TPL 任务?

c# - LINQ:如何在Include中引入where?

c# - C# 中的任务并行库和 PLINQ 替代方案

c# - TPL Fire and Forget 使用单独的类

c# - 异步在 ASP.NET Web 应用程序中如何工作?