Loading ...

Parallel programming is not always the fastest way

Who is online?  0 guests and 0 members
home  »  articles  »  Parallel programming is not always the fastest way

Parallel programming is not always the fastest way

(1012)
0
/5
Avg: 0/5: (0 votes)
Published: 6/21/2010 by  Prahlad Kumar

download source 

 

Introduction

In this article i'm going to analyse Parallel.For and for loop in different workload.

 

Background

It is always recommended to use Parallel.For if you have big code under loop. For small chunks of code serial for loop should be used. Reason for this is that with parallel programming there is overhead of multiple tasks(or threads). That can slow down performance of you application if compared to serial programming. Let's examine this with different situation.

Implementation Detail

 

  • There are 2 methods serialShow and ParallelShow. SerialShow display content of a List<string> element using serial for loop. ParallelShow did the same job using Parallel.For. a Stopwatch is used to calculate time elapsed. 
  • in 2nd round of testing i increased overhead of SerialShow and ParallelShow method using adding Thread.Sleep(500). 
Code

 

  static void serialShow()

        {

            for (int i = 0; i < 10; i++)

            {

                //System.Threading.Thread.Sleep(500);

                Console.WriteLine(string.Format("i \t {0}",names[i]));

            }

        }

        static void ParallelShow()

        {

            Parallel.For(0,names.Count,i=>

            {

                //System.Threading.Thread.Sleep(500);

                Console.WriteLine(string.Format("i \t {0}",names[i]));

            });

        }

There is the simplest code in this both methods to demonstrate it's efficiency. in different run to test in heavy workload in methods we only need to uncomment Thread.Sleep(500).

Sample output

Let's see out put of this program when Thread.Sleep is commented.

Here Total time taken by serialShow  is 0.0007819 second and ParallelShow  took 0.0264595.

Now let's uncomment the thread.Sleep code and give some workload here. and see what is the output.

Here, serialShow() took 5.0015387 and ParallelShow() took 2.0070997 seconds.

Conclusion

So, I would like to conclude this discussion with :- "Parallel programming cannot be fastest way to complete task. if not chosen carefully, it can slowdown the application."

References :-

.NET 4.0 with Visual Studio 2010, Alex Mackey, Apress

 

 

Comments (no comments yet)

  • Name:*
  • Email:*
  • Website:
Type the characters you see in the image *

Confirm

Product Spotlight

ASP.NET Hosting Spotlight

Most Recent Articles

 

Product Spotlight

ASP.NET Hosting Spotlight

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?