Naveen's Weblog

Bridge to future

Performance difference between For and Parallel.For

Posted by codingsense on October 17, 2009


Hi,
I was really happy when i heard of the concept of Parallel.For that is introduced in new version of .Net. I tried it in framework 4.0 in visual studio 2010.
Here is the sample that i ran to see how the performance will vary on my system ( Core 2 duo).

class Program
    {
        static void Main(string[] args)
        {
            long[] a = new long[1000000];

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            Parallel.For(0, 1000000, delegate(long i)
            {
                a[i] = i * i;
            });

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Start();

            for (long I = 0; I < 1000000; I++)
            {
                a[I] = I * I;
            }

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.Read();
        }
    }

What i saw is always there is a differnce in value depending on the work load on each core. But to my surprise i found that in all the 10-15 cases that i ran, for loop took less time to execute than Parallel.For.
I think there might be some other things that needs to be done to make use of Parallel.For to make it more efficient than For or there might be some specific tasks where Parallel.For should be used.
Will try to find it out and get back to you soon.

Naveen Prabhu

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: