Click here to Skip to main content
13,046,773 members (58,545 online)
Rate this:
Please Sign up or sign in to vote.
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.
public void Calculate()
            int iterate = 0;
            while (iterate < 4000)
                //Do Work

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

Your time is very much appreciated,

Posted 27-May-10 0:07am
Updated 27-May-10 2:25am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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:
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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 27 May 2010
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100