Ale*_*dar 35 c# parallel-processing
在我的应用程序中,我从几十个执行到几百个并行操作(没有操作的返回值).
哪种方法最优:
Task.Factory.StartNew在foreach循环中使用迭代遍历Action数组(Action[])
Task.Factory.StartNew(() => someAction());
使用Parallel类其中actions是Action阵列(Action[])
Parallel.Invoke(actions);
这两种方法是否相同?是否有任何性能影响?
编辑
我已经执行了一些性能测试,并且在我的机器上(每个2个CPU 2核心)结果似乎非常相似.我不确定它在1 CPU等其他机器上会是什么样子.另外我不确定(不知道如何以非常准确的方式测试它)什么是内存消耗.
Str*_*ior 44
这两者之间最重要的区别在于,Parallel.Invoke在继续使用代码之前将等待所有操作完成,而StartNew将继续执行下一行代码,允许任务在他们自己的好时间内完成.
这种语义差异应该是您的第一个(也可能是唯一的)考虑因素.但出于提供信息的目的,这是一个基准:
/* This is a benchmarking template I use in LINQPad when I want to do a
* quick performance test. Just give it a couple of actions to test and
* it will give you a pretty good idea of how long they take compared
* to one another. It's not perfect: You can expect a 3% error margin
* under ideal circumstances. But if you're not going to improve
* performance by more than 3%, you probably don't care anyway.*/
void Main()
{
// Enter setup code here
var actions2 =
(from i in Enumerable.Range(1, 10000)
select (Action)(() => {})).ToArray();
var awaitList = new Task[actions2.Length];
var actions = new[]
{
new TimedAction("Task.Factory.StartNew", () =>
{
// Enter code to test here
int j = 0;
foreach(var action in actions2)
{
awaitList[j++] = Task.Factory.StartNew(action);
}
Task.WaitAll(awaitList);
}),
new TimedAction("Parallel.Invoke", () =>
{
// Enter code to test here
Parallel.Invoke(actions2);
}),
};
const int TimesToRun = 100; // Tweak this as necessary
TimeActions(TimesToRun, actions);
}
#region timer helper methods
// Define other methods and classes here
public void TimeActions(int iterations, params TimedAction[] actions)
{
Stopwatch s = new Stopwatch();
int length = actions.Length;
var results = new ActionResult[actions.Length];
// Perform the actions in their initial order.
for(int i = 0; i < length; i++)
{
var action = actions[i];
var result = results[i] = new ActionResult{Message = action.Message};
// Do a dry run to get things ramped up/cached
result.DryRun1 = s.Time(action.Action, 10);
result.FullRun1 = s.Time(action.Action, iterations);
}
// Perform the actions in reverse order.
for(int i = length - 1; i >= 0; i--)
{
var action = actions[i];
var result = results[i];
// Do a dry run to get things ramped up/cached
result.DryRun2 = s.Time(action.Action, 10);
result.FullRun2 = s.Time(action.Action, iterations);
}
results.Dump();
}
public class ActionResult
{
public string Message {get;set;}
public double DryRun1 {get;set;}
public double DryRun2 {get;set;}
public double FullRun1 {get;set;}
public double FullRun2 {get;set;}
}
public class TimedAction
{
public TimedAction(string message, Action action)
{
Message = message;
Action = action;
}
public string Message {get;private set;}
public Action Action {get;private set;}
}
public static class StopwatchExtensions
{
public static double Time(this Stopwatch sw, Action action, int iterations)
{
sw.Restart();
for (int i = 0; i < iterations; i++)
{
action();
}
sw.Stop();
return sw.Elapsed.TotalMilliseconds;
}
}
#endregion
Run Code Online (Sandbox Code Playgroud)
结果:
Message | DryRun1 | DryRun2 | FullRun1 | FullRun2
----------------------------------------------------------------
Task.Factory.StartNew | 43.0592 | 50.847 | 452.2637 | 463.2310
Parallel.Invoke | 10.5717 | 9.948 | 102.7767 | 101.1158
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,使用Parallel.Invoke比等待一堆新的任务完成要快大约4.5倍.当然,那是你的行为什么都不做的时候.每个动作越多,你会注意到的差异越小.
Col*_*kay 13
在宏观方案中,当考虑在任何情况下实际处理大量任务的开销时,两种方法之间的性能差异可以忽略不计.
在Parallel.Invoke基本上执行的Task.Factory.StartNew()为您服务.所以,我认为可读性在这里更重要.
另外,正如StriplingWarrior所提到的,Parallel.Invoke执行a WaitAll(阻止代码直到完成所有任务),所以你也不必这样做.如果您想让任务在后台运行而不需要关心,那么您需要Task.Factory.StartNew().
Alo*_*aus 12
我使用了StriplingWarror中的测试来找出差异的来源.我这样做是因为当我在代码中查看Reflector时,Parallel类与创建一堆任务没什么不同,让它们运行.
从理论的角度来看,两种方法在运行时间方面应该是等价的.但是,使用空操作的(不太现实)测试确实表明Parallel类更快.
任务版本确实花费了大部分时间来创建新任务,这会导致许多垃圾收集.您看到的速度差异纯粹是因为您创建了许多快速变成垃圾的任务.
而Parallel类确实创建了自己的任务派生类,它在所有CPU上并发运行.在所有核心上只运行一个物理任务.同步确实发生在任务委托中,这确实解释了Parallel类更快的速度.
ParallelForReplicatingTask task2 = new ParallelForReplicatingTask(parallelOptions, delegate {
for (int k = Interlocked.Increment(ref actionIndex); k <= actionsCopy.Length; k = Interlocked.Increment(ref actionIndex))
{
actionsCopy[k - 1]();
}
}, TaskCreationOptions.None, InternalTaskOptions.SelfReplicating);
task2.RunSynchronously(parallelOptions.EffectiveTaskScheduler);
task2.Wait();
Run Code Online (Sandbox Code Playgroud)
那么最好的是什么呢?最好的任务是永不运行的任务.如果您需要创建如此多的任务以使它们成为垃圾收集器的负担,您应该远离任务API并坚持使用Parallel类,它可以在没有新任务的情况下在所有核心上直接并行执行.
如果您需要变得更快,可能是手动创建线程并使用手动优化的数据结构为您的访问模式提供最大速度是最高性能的解决方案.但是你不可能成功地这样做,因为TPL和并行API已经大量调整.通常,您需要使用众多重载中的一个来配置正在运行的任务,或者使用Parallel类来实现相同的代码.
但是如果你有一个非标准的线程模式,那么你最好不要使用TPL来充分利用核心.甚至Stephen Toub确实提到TPL API不是为超快速性能而设计的,但主要目标是让"普通"程序员更容易进行线程化.要在特定情况下击败TPL,你需要远高于平均水平,你需要了解很多关于CPU缓存行,线程调度,内存模型,JIT代码生成的东西,...在你的特定场景中出现一些东西更好.