我最近搬到了C#.net 4。何时使用Parallel.For?
我喜欢Parallel.For,但不知道什么时候用,什么时候不用。 我知道,当订单对我不重要时 - 我会使用它。
但是有没有关于使用Parallels的开销的任何测试?意思是,如果我的循环只运行10次(并且执行的逻辑非常少) - 我应该避免使用Parallels吗?有没有任何拇指规则?
我最近搬到了C#.net 4。何时使用Parallel.For?
我喜欢Parallel.For,但不知道什么时候用,什么时候不用。 我知道,当订单对我不重要时 - 我会使用它。
但是有没有关于使用Parallels的开销的任何测试?意思是,如果我的循环只运行10次(并且执行的逻辑非常少) - 我应该避免使用Parallels吗?有没有任何拇指规则?
我会避免使用Parallel.For
,除非性能是一个问题。
同时运行的编写代码通常比编写单线程代码更困难。此外,如果由于并发问题而导致错误,则可能很难对其进行调试。例如,错误可能只是有时发生,不容易重现。除非你有特别需要提高性能,否则我建议你保持简单并在单个线程上使用普通循环。
我同意 - 不要”不要只是使用它,因为它在那里,试着解决它的一个实际问题。此外,分析是你的朋友;) – 2010-09-15 08:27:20
我认为“表现是一个问题”在这里暗示。 – 2010-09-15 08:34:33
我同意马克。尽可能少的资源用于工作。 – Josh 2010-09-15 12:38:12
引用SQLite常见问题:'Threads are evil。避免它们'
并行性对于性能很有用。应用程序性能优化是软件设计中最不直观的事情之一,应该非常谨慎地使用正确的测量工具来完成,否则它会显得很有趣。
有些人会优化用户界面代码,以微秒而不是毫秒响应,显然没有价值并造成很大的损害。
这其中的一些事实,但太简单了。请参阅http:// stackoverflow。COM /问题/ 3415519/IS-有-A-点对多线程/ 3415563#3415563 – 2010-09-15 08:33:07
Parallel.For循环使用ThreadPool通过在循环的每次迭代中调用一次委托来执行循环中的工作。
怎样的Parallel.For作品可以呈现如下总体思路:
public static void MyParallelFor(int inclusiveLowerBound, int exclusiveUpperBound, Action<int> body)
{
// Get the number of processors, initialize the number of remaining
// threads, and set the starting point for the iteration.
int numProcs = Environment.ProcessorCount;
int remainingWorkItems = numProcs;
int nextIteration = inclusiveLowerBound;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
// Create each of the work items.
for (int p = 0; p < numProcs; p++)
{
ThreadPool.QueueUserWorkItem(delegate
{
int index;
while ((index = Interlocked.Increment(ref nextIteration) - 1) < exclusiveUpperBound)
body(index);
if (Interlocked.Decrement(ref remainingWorkItems) == 0)
mre.Set();
});
}
// Wait for all threads to complete.
mre.WaitOne();
}
}
的Parallel.For返回ParallelLoopResult值类型,其中包含已完成的循环细节。它的一个过载如下:
public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
认识到并行执行并不总是比串行执行更快是很重要的。为了决定是否使用并行,你必须估算循环迭代所要做的工作量。如果循环执行的实际工作相对于线程同步成本较小,则最好使用普通循环。
这是例子之一,当连续的循环性能更快平行:
static void Main(string[] args)
{
Action<int> action = new Action<int>(SimpleMethod);
// ordinary For loop performance estimation
var sw = Stopwatch.StartNew();
for(int i = 0; i < 1000; i++)
action(i);
Console.WriteLine("{0} sec.", sw.Elapsed.TotalSeconds);
// parallel For loop performance estimation
sw = Stopwatch.StartNew();
Parallel.For(0, 1000, action);
Console.WriteLine("{0} sec.", sw.Elapsed.TotalSeconds);
}
static void SimpleMethod(int index)
{
int d = 1;
int result = index/d;
}
输出:
0.0001963 sec.
0.0346729 sec.
下面是微软一个很好的免费的电子书,涵盖了这个话题“ [并行编程模式:了解和应用与.NET Framework 4并行模式](https://www.microsoft.com/en-us/download/details.aspx?id=19222)“ – 2017-07-03 17:50:26