Loading ...

Parallel programming is not always the fastest way | CodeAsp.Net

Parallel programming is not always the fastest way

 /5
0 (0votes)

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 (3)

   
Yahoo Support Number

Parallel programming is really good now a day. Thanks for sharing.

10/6/2016
 · 
by
   
Manchun

this is nice article, can i publish article on this website.

1/9/2017
 · 
by
   
JanBask

Parallel programming cannot be fastest way to complete task. if not chosen carefully, it can slowdown the application. nice article thank you

1/10/2017
 · 
by
  • :*
  • :*
  • :
 *

Top Articles