Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is the best way to do a parallel loop.
For example
C#
for(int i = 0; i < 1424;i++)
{
    call some function
}

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

Thanks
Posted
Updated 3-Dec-12 12:02pm
v2

1 solution

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
 
Share this answer
 
Comments
Espen Harlinn 3-Dec-12 19:31pm    
That's often the case :-D
Sometimes blocking IO can benefit from parallel execution too ...
Sergey Alexandrovich Kryukov 3-Dec-12 21:54pm    
True. Thank you, Espen.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900