什么时候使用Partitioner类? [英] When to use Partitioner class?

查看:101
本文介绍了什么时候使用Partitioner类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以建议可以/应该使用.NET 4.0中引入的 Partitioner 类的典型方案吗?

Can anyone suggest typical scenarios where Partitioner class introduced in .NET 4.0 can/should be used?

推荐答案

Partitioner 类用于使并行执行更加块化。如果您有很多非常小的任务要并行运行,则为每个调用委托的开销可能会过高。通过使用 Partitioner ,您可以将工作负载重新排列为多个块,并使每个并行调用工作在稍大的集合上。该类抽象了此功能,并能够根据数据集和可用核心的实际条件进行分区。

The Partitioner class is used to make parallel executions more chunky. If you have a lot of very small tasks to run in parallel the overhead of invoking delegates for each may be prohibitive. By using Partitioner, you can rearrange the workload into chunks and have each parallel invocation work on a slightly larger set. The class abstracts this feature and is able to partition based on the actual conditions of the dataset and available cores.

示例:假设您想并行运行这样的简单计算。

Example: Imagine you want to run a simple calculation like this in parallel.

Parallel.ForEach(Input, (value, loopState, index) => { Result[index] = value*Math.PI; });

这将为Input中的每个条目调用委托。这样做会给每个服务器增加一些开销。通过使用 Partitioner 我们可以执行以下操作

That would invoke the delegate for each entry in Input. Doing so would add a bit of overhead to each. By using Partitioner we can do something like this

Parallel.ForEach(Partitioner.Create(0, Input.Length), range => {
   for (var index = range.Item1; index < range.Item2; index++) {
      Result[index] = Input[index]*Math.PI;
   }
});

这将减少调用次数,因为每个调用将在更大的集合上工作。以我的经验,这可以在并行化非常简单的操作时显着提高性能。

This will reduce the number of invokes as each invoke will work on a larger set. In my experience this can boost performance significantly when parallelizing very simple operations.

这篇关于什么时候使用Partitioner类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆