Click here to Skip to main content
15,902,276 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day all,

I have an application that needs to run a specific function up to 100,000 times. A function called Calculate() has within it an iteration loop that runs 100,000 times.


Currently doing this takes 104 seconds. What I would like to be able to do it rather than have it set at 100,000 iterations, have it set at 4,000 and run Calculate() seperately on 25 threads.
C#
public void Calculate()
        {
            int iterate = 0;
            
            
            while (iterate < 4000)
            {
                    
                //Do Work

                iterate++;
            }
            
        }


Can anyone explain using my example above how I can do this?

Your time is very much appreciated,

Mike.
Posted
Updated 27-May-10 2:25am
v2

It looks like you could replace that function with a for loop. If so you could try using the new Parallel class in .Net 4. You won't have to split the tasks up yourself as I believe it includes it's own 'load balancing' for threads.
 
Share this answer
 
Like Tony said, if you can use .NET 4, you could use the new Parallel stuff. I started using that myself, almost reduces the elapsed time by half on my dual core processor. Here is a good article how to do it. Considering your code example:
MIDL
public void Calculate()
        {
            System.Threading.Tasks.Parallel.For(0, 100000,
                i =>
                {
                    //You have access to i here
                    //Do work.
                }
            );
        }

Hope that helps,
Anıl Yıldız.
 
Share this answer
 
Comments
William Winner 27-May-10 18:12pm    
well since, theoretically, it can now use both cores instead of one, you would expect it to be reduced about in half...there's a bit more overhead, so not exactly half, but close.
Anıl Yıldız 27-May-10 18:15pm    
Indeed, thats the "almost" keyword was for.
Jibrohni 28-May-10 5:54am    
Thanks to both. I managed to get it runnning on 8 seperate threads (seemed to give the quickest results). What started at 1 min 40 is now down to 26 seconds. I'm going to start again as I'm still perfecting my use of encapsulation amongst other concepts.

I had a quick look at the parallel For but it's still a little above my station. I'll repost when I get back to this point, hopefully I'll have streamlined my code as I want it ideally down to no more than 10 seconds.

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