Geeks With Blogs

News

View Anthony Trudeau's profile on LinkedIn

Add to Technorati Favorites


Anthony Trudeau

The latest MSDN magazine has an article by Stephen Toub, Igor Ostrovsky, and Huseyin Yildiz called "False Sharing" (http://msdn.microsoft.com/en-us/magazine/cc872851.aspx).  Early in the article the author puts out the argument that memory access patterns are important.  And he provides an example.

The example (listed below) is a simple program that creates a multi-dimensional array, iterates through it, and displays the time it took.  The program first goes through each row and each column of each row for the first test and then through each column and each row of the column for the second test.  The results are eye opening.  The latter test runs over 2x slower on my computer (your results may vary).  Specifically, the first test runs in just less than a second whereas the second test runs consistently over 2.5 seconds.

The reason the second test is slower is that the memory in the array is laid out continguously.  When you access the array the value as well as values around it will be loaded into the cache line.  The more often you navigate to different rows the more penalty you incur in memory access.

I know I'm guilty of focusing on other issues besides memory access.  I think we get lulled into the believe that we're not dealing with C++ so we don't have to consider memory in the same ways.  This example proves otherwise.

using System;

using System.Diagnostics;

 

namespace MemoryAccessTest

{

    class Program

    {

        static void Main(string[] args)

        {

            const int size = 10000;

            int[,] matrix = new int[size, size];

            Stopwatch sw;

 

            while (true)

            {

                // faster loop

                sw = Stopwatch.StartNew();

 

                for (int row = 0; row < size; row++)

                    for (int column = 0; column < size; column++)

                        matrix[row, column] = (row * size) + column;

 

                Console.WriteLine("elapsed: {0}", sw.Elapsed.ToString());

                sw.Reset();

 

                // slower loop

                sw.Start();

 

                for (int column = 0; column < size; column++)

                    for (int row = 0; row < size; row++)

                        matrix[row, column] = (row * size) + column;

 

                Console.WriteLine("elapsed: {0}", sw.Elapsed.ToString());

                sw.Stop();

 

                Console.WriteLine(new string('=', 20));

                Console.ReadLine();

            }

        }

    }

}

Posted on Thursday, October 16, 2008 5:28 PM .NET | Back to top


Comments on this post: Memory Access Patterns are Important

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Anthony Trudeau | Powered by: GeeksWithBlogs.net