Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a sequential loop as...

C#
for (int i = 0; i < 1000;i++ )
            {
                Console.WriteLine(i);
            }

and execution time for this loop is some t microsecond.now i want to make it parllel with my i5 processor of 4 cores. so that i can reduce the execution time for it.. so i had written this code...


C#
int N=1000;
Parallel.For(0, N, delegate(int i) 
                {
                    Console.WriteLine(i);
                });

but this took execution time more than t ,, pls help me in this.. :(
Posted
Updated 30-Mar-12 23:46pm
v2
Comments
fct2004 31-Mar-12 21:52pm    
I'm sorry, but are you asking for help to make something run faster, or are you asking for help to know why it didn't run faster?
KUNWAR999 1-Apr-12 5:17am    
i want to make it run faster in parllel code than sequential code.. do you know how can i do that.. ??
fct2004 1-Apr-12 7:26am    
I don't know of anything that can make this run faster in parallel code. A normal for loop is about the fastest this is going to get for two reasons.

1. There is more overhead in a parallel loop than a normal loop.
2. Writing to the same console in parallel won't speed it up because we are being limited by the I/O stream, not the CPU.

If you were doing actual computation inside the body of the loop, we might be able to help you speed it up by running the loops in parallel.

The sort answer is no. You cannot speedup the body of this specific loop by running it in parallel.

1 solution

I have not used Parallel myself but I would suggest that the Console.WriteLine(i); statements will slow things down, as both will be contending for shared resources.
 
Share this answer
 
Comments
KUNWAR999 31-Mar-12 6:13am    
if i use some other statement instead of Console.WriteLine(i.. then it again shows same problem.. :(
Richard MacCutchan 31-Mar-12 6:44am    
What statement? Anything that requires a shared resource, such as writing to the console or a file will slow things down. Using parallel threads is only any use if you have code that uses simple CPU processing; once you go outside that area then you will start to hit all sorts of operating system blocks.
KUNWAR999 31-Mar-12 7:08am    
i used i++; inplace of Console.WriteLine(i);
it gives 312 microseconds for sequential code and 2361 microseconds for parllel code..
Richard MacCutchan 31-Mar-12 8:05am    
This suggests that parallel operations for a simple loop do not offer any benefits. I would suggest you study the details of the Parallel class to see what benefits they offer.

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