gpt4 book ai didi

c# - MaxDegreeOfParallelism 为 1 的 for 循环和 Parallel.For() 之间的性能损失

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:03 27 4
gpt4 key购买 nike

我想做如下的事情:

int firstLoopMaxThreads = 1; // or -1
int secondLoopMaxThreads = firstLoopMaxThreads == 1 ? -1 : 1;

Parallel.For(0, m, new ParallelOptions() { MaxDegreeOfParallelism = firstLoopMaxThreads }, i =>
{
//do some processor and/or memory-intensive stuff
Parallel.For(0, n, new ParallelOptions() { MaxDegreeOfParallelism = secondLoopMaxThreads }, j =>
{
//do some other processor and/or memory-intensive stuff
});
});

当 secondLoopMaxThreads = 1 时,将内部 Parallel.For 循环与普通 for 循环交换是否值得,从性能角度来看?常规 for 循环与 Parallel.For 循环(MaxDegreeofParallelism = 1)之间的性能差异是什么?

最佳答案

这取决于您谈论的迭代次数以及您谈论的性能水平,以回答是否值得。在您的上下文中,1 毫秒被认为是很多还是很少?

我做了一个基本的测试如下(因为 Thread.Sleep 并不完全准确.. 尽管 for 循环每次测量 15,000ms 到 1ms 以内)。超过 15,000 次迭代重复 5 次,与标准 for 循环相比,它通常会增加大约 4 毫秒的开销……但当然结果会因环境而异。

for (int z = 0; z < 5; z++)
{
int iterations = 15000;

Stopwatch s = Stopwatch.StartNew();

for (int i = 0; i < iterations; i++)
Thread.Sleep(1);

s.Stop();

Console.WriteLine("#{0}:Elapsed (for): {1:#,0}ms", z, ((double)s.ElapsedTicks / (double)Stopwatch.Frequency) * 1000);

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
s = Stopwatch.StartNew();

Parallel.For(0, iterations, options, (i) => Thread.Sleep(1));

s.Stop();

Console.WriteLine("#{0}: Elapsed (parallel): {1:#,0}ms", z, ((double)s.ElapsedTicks / (double)Stopwatch.Frequency) * 1000);
}

关于c# - MaxDegreeOfParallelism 为 1 的 for 循环和 Parallel.For() 之间的性能损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169326/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com