为什么C#任务并行库代码比普通的for循环慢?

为什么C#任务并行库代码比普通的for循环慢?,c#,performance,task-parallel-library,C#,Performance,Task Parallel Library,我想知道为什么并行代码不比使用此代码的正常循环快: class MainClass { public static int count = 0; public static void Main (string[] args) { int range = 1000000; Stopwatch sp = new Stopwatch (); sp.Start (); Parallel.For (0, range,

我想知道为什么并行代码不比使用此代码的正常
循环快:

class MainClass
{
    public static int count = 0;

    public static void Main (string[] args)
    {
        int range = 1000000;
        Stopwatch sp = new Stopwatch ();
        sp.Start ();
        Parallel.For (0, range, (i) => {
            count = count + i;
            Console.WriteLine ("Current sum is " + count);
        });
        sp.Stop ();
        Console.WriteLine ("time to add was " + sp.ElapsedMilliseconds);

        Console.ReadLine ();

        Stopwatch s = new Stopwatch ();
        s.Start ();
        for (int i = 0; i < range; i++) {
            count = count + i;
            Console.WriteLine ("Current sum is " + count);
        }
        s.Stop ();
        Console.WriteLine ("time to add was " + s.ElapsedMilliseconds);
    }
}
class类main类
{
公共静态整数计数=0;
公共静态void Main(字符串[]args)
{
整数范围=1000000;
秒表sp=新秒表();
sp.Start();
平行。对于(0,范围,(i)=>{
计数=计数+i;
Console.WriteLine(“当前总和为”+计数);
});
sp.Stop();
Console.WriteLine(“添加时间为”+sp.elapsedmillyses);
Console.ReadLine();
秒表s=新秒表();
s、 开始();
对于(int i=0;i
要获得更准确的结果,请删除对两个循环中的
控制台.WriteLine
的调用。由于问题注释中所述的原因,您仍然会看到并行循环速度较慢

为了更好地理解原因,请改用重载
Parallel.for
from,并将属性
ParallelOptions.MaxDegreeOfParallelism
设置为4(允许最多4个并发操作)或-1(无限制),并且由于线程处理开销,Parallel for循环会如预期的那样变慢。现在将
ParallelOptions.MaxDegreeOfParallelism
设置为1,这意味着只有1个线程将处理循环操作。现在应该会导致类似的时间安排吗

现在结果更接近了,但并行循环仍然较慢。我认为这是因为并行循环仍然需要处理线程并以某种方式与任务调度器进行交互,而普通循环根本不需要


我希望这个答案能给您提供更多的见解。

我将您的问题迁移到堆栈溢出,因为您的问题是“为什么我的代码会以这种方式运行?”而不是“如何改进我的代码?”除此之外,您的代码不是线程安全的。您正在多个线程中以不安全的方式改变共享状态。无论如何,你可能不会得到同样的结果。除此之外,您代码中的绝大多数时间都将花费在
控制台.WriteLine
中。并行内部的代码。因为实际上没有做任何事情,所以您只测量PLINQ的开销。由于生成和处理线程的开销,这是为什么被否决的?