Saturday, February 28, 2015

The Parallel For Method


using System.Windows.Forms;
using System.Collections.Concurrent; //Added to use BlockingCollection
using System.Diagnostics; //Added to use stop watch.

namespace The_Parallel_For_Method
{

    public partial class Form1 : Form
    {
        //Parallel class defines for, foreach, and Invoke methods
        //The parallel.For is a method that runs like the regular for loop
        //except that each cycle, or iteration runs in its own task.
        //It likes starting multiple tasks that run concurrently.

        List<double> resultList = new List<double>();
        BlockingCollection<double> parallelResultList = new BlockingCollection<double>();

        public Form1()
        {
            InitializeComponent();
        }

        private void btnCompareForLoopWithParallelFor_Click(object sender, EventArgs e)
        {
            //use StopWatch to time each for loop
            Stopwatch sw = new Stopwatch();
            richTextBox1.Text = "Starting timer for forloop \n";
            sw.Start();
            //regular / sequential for loop
            for (int root = 1; root <= 5000; root++)
            {
                double result = SumRootN(root);
                resultList.Add(result);
            }
            sw.Stop();
            //=====================Using a Parallel.For

            richTextBox1.AppendText("Sequential for loop time: " + sw.Elapsed.ToString() + "\n");
            sw.Restart();

            Parallel.For(1, 5001, (root) =>
                {
                    double result = 0;
                    for (int i = 1; i <= 10000; i++)
                    {
                        result += Math.Exp(Math.Log(i) / root);
                    }
                    parallelResultList.Add(result);

                });
           
            sw.Stop();
            richTextBox1.AppendText("Parallel for loop time: " + sw.Elapsed.ToString() + "\n");
        }

        //computes sum root of a number
        static double SumRootN(int root)
        {
            double result = 0;
            for (int i = 1; i <= 10000; i++)
            {
                result += Math.Exp(Math.Log(i) / root);
            }
            return result;
        }
    }
}
////msdn.microsoft.com/en-us/library/dd783539(v=vs.110).aspx
//Lab: 
//In a console application to observe the index cycle
//run the parallel.For for the sumroot for up to 100
//display index cycle and result.
//
//You should notice that the cycles don't run in any predetermined 
//sequence

No comments:

Post a Comment