C#中的并行For循环 [英] Parallel For loops in C#

查看:457
本文介绍了C#中的并行For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行并行循环的最佳方法是什么。

例如

what is the best way to do a parallel loop.
For example

for(int i = 0; i < 1424;i++)
{
    call some function
}



喜欢将它分配到1424 / n个部分然后应用相同的功能。我是否正确理解并行性?



谢谢


Like to distribute this into 1424/n sections and then apply the same function. Am I understanding parallelism correctly?

Thanks

推荐答案

这是最简单的并行形式: http://msdn.microsoft.com/en- us / library / dd783539.aspx [ ^ ]。



请参阅其他人: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.aspx [ ^ ]。



你明白吗?基本上,是的,但你也应该了解一些相关的问题。最重要的是,并行执行基于线程,并且任务在线程上自动分派。这种机制本身有很大的开销。因此,例如,如果您只有一个CPU代码(或者没有足够的内核),那么您将无法获得任何吞吐量,只会使用。它还取决于系统中活动(意义,非等待)状态下的许多其他进程。粗略地说,它们会占用CPU时间,并且平均会给你留下不到一个代码,所以你会失去性能,而不是获得。此外,循环体中调用的动作应该是高度独立的。如果他们相互等待相当长的时间,即使其他进程根本没有使用CPU资源,你也会在整体吞吐量方面松动。



由于所有这些原因,从并行循环中获得性能的过程并不常见。关于开发人员之间的并行执行能力存在很多误解。



-SA
This is the simplest Parallel form of it: http://msdn.microsoft.com/en-us/library/dd783539.aspx[^].

Please see others: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.aspx[^].

Do you understand it right? Basically, yes, but you should also understand a number of related issues. Most importantly, parallel executions is based on threads, and the tasks are automatically dispatched on the threads. This mechanism itself has considerable overhead. So, if, for example, you have only one CPU code (or not enough cores), you will not gain any throughput, will only use. It also depends on a number of other processes on the system in active (meaning, non-wait) states. Roughly speaking, they will eat up CPU time and will leave you with less then one code, on average, so you will loose performance, not gain. Also, the actions called in the loop body should be highly independent. If they wait for each other for considerable amount of time, you will, again, loose in overall throughput even if other processes don''t use CPU resources at all.

Due to all that reasons, the processes which gain performance from parallel loops are not so typical. There are a lot of misconception about a power of parallel execution among developers.

—SA


这篇关于C#中的并行For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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