Monday, July 5, 2010

Parallel For and ForEach in .Net 4

I've started looking at the Parallel.For and Parallel.ForEach methods from .Net 4's Task Parallel Library. Before I use something as complex and potentially dangerous as this I like to test it out to make sure I'm going to get that performance boost before going down that path.




Here's the console app that I wrote to do the test:

static void Main(string[] args)
{
    int[] someInts = Enumerable.Range(0, 100).ToArray();

    Stopwatch timer = Stopwatch.StartNew();
    foreach (int item in someInts)
    {
        DoItem(item);
    }
    Console.WriteLine("Sequential: {0}", timer.Elapsed);

    timer.Restart();
    Parallel.ForEach(someInts, item => DoItem(item));
    Console.WriteLine("Parallel: {0}", timer.Elapsed);

    Console.ReadKey();
}

static void DoItem(int item)
{
    Random r = new Random((int)DateTime.Now.Ticks);
    for (int i = 0; i < (item * 100000); i++)
    {
        int j = r.Next(0, 10000);
        j = j * j;
    }
}


I ran this a number of times on a quad core machine (Intel Core2 Quad Q9400 @ 2.66GHz) on Windows 7 x64. Average time for the sequential loop was 14.7 seconds and for the parallel loop was 5.6 seconds for a ratio of 2.6 times faster using the parallel loop. This is seems right., you're going to get a loop like this to be about Core-1 times faster because the thread management will "cost" you one of your cores. So on an 8 core machine expect this loop to be 7 times faster and on a quad expect 3 times which is what I almost got.


No comments:

Post a Comment