Parallel.For Faster Than Regular For?

In the recent MSDN magazine I read an article espousing the wonders of parallel processing.  Ever since I forked my first threat back in school, I’ve liked the idea.  However since joining the world of business programming I’ve seldom come across it in use with legitimacy or the desired effect.

Take this extremely simple example in .Net 4 WinForm (It’s a Form with 2 buttons and 2 Textboxes.  Below is the code:

        private void button1_Click(object sender, EventArgs e)
        {
            Stopwatch sw = Stopwatch.StartNew();

            int x = 1;

            for (int i = 0; i < 1000000000; i++)
            {
                x *= i;
            }

            sw.Stop();
            textBox1.Text = "Total Time: " + sw.ElapsedMilliseconds;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stopwatch sw = Stopwatch.StartNew();

            int x = 1;
            System.Threading.Tasks.Parallel.For(0, 1000000000, i =>
            {
                x *= i;
            });

            sw.Stop();
            textBox2.Text = "Total Time: " + sw.ElapsedMilliseconds;
        }

Results?  Regular For Loop wins hands down and consistently.  I have to wonder, why is it slower?  To answer that, I found the following link:

http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/2468e6ee-f551-42c4-a404-dfb051ac2614

Answer:

To be more specific, your workload per iteration is extremely short (access by index, and increment a single integer) – and this allows the cost of synchronizing the worker threads to become more significant than the workload itself. If you try longer workloads in the delegate, you should observe better results.

Hmm…  So, it’s because I was just doing simple math?

Another interesting thread I found on the issue that has a more complex test:

http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/6bd174ea-3a29-441b-a43f-e61d44497029/

I will try some further testing in the future with more complex math and different hardware configurations to confirm what is said in that post.

Made for a little fun though; hope you enjoy.

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *