赵劼老师的教导

来源:互联网 发布:投稿论文中数据算错 编辑:程序博客网 时间:2024/06/10 14:56

我们先来看一个例子。例如,我们现在有一个二维数组:

static void Main(string[] args)
{
    int n = 1 << 10;
    int[,] array = new int[n, n];

    for (int x = 0; x < n; x++)
    {
        for (int y = 0; y < n; y++)
        {
            array[x, y] = x;
        }
    }

    ...
}

  我们要对这个1024 * 1024的二位数组中所有元素求和。那么我们会怎么写呢?先随手写一把:

static int SumA(int[,] array, int n)
{
    int sum = 0;
    for (int y = 0; y < n; y++)
    {
        for (int x = 0; x < n; x++)
        {
            sum += array[x, y];
        }
    }

    return sum;
}

  一个二重循环,遍历二维数组中每一个元素,相加,这也太容易了吧?是啊,不过我们还是可以“换种写法”的:

static int SumB(int[,] array, int n)
{
    int sum = 0;
    for (int x = 0; x < n; x++)
    {
        for (int y = 0; y < n; y++)
        {
            sum += array[x, y];
        }
    }

    return sum;
}

  仔细看看,有没有发现区别?没错,只是内层循环和外层循环的位置换了一下。这么做的意义何在?测试一下便知:

static void TestLocality(int[,] array, int n)
{
    Stopwatch watch1 = new Stopwatch();
    watch1.Start();
    for (int i = 0; i < 100; i++) SumA(array, n);
    watch1.Stop();
    Console.WriteLine("SumA: " + watch1.Elapsed);

    Stopwatch watch2 = new Stopwatch();
    watch2.Start();
    for (int i = 0; i < 100; i++) SumB(array, n);
    watch2.Stop();
    Console.WriteLine("SumB: " + watch2.Elapsed);
}
  我们把两种加法各执行100次,看看结果:

SumA: 00:00:04.8116776
SumB: 00:00:00.8342202
 

老赵就是牛,这事情我之前从不考虑,现在看,时间竟然差了这么多,这不是说我们半路出家人的学习难度更大了。

其实更重要的是告诉我们要扎扎实实的学习,打好基础是今后腾飞的基础。嗯,看来我的电动力学,量子力学,数学分析之类的又要好好复习一下了。话说中国当今浮躁盛行,谁能稳住心谁更容易成功。

欲知上事为何,请看老赵分解:

http://www.cnblogs.com/JeffreyZhao/archive/2009/01/22/system-architecture-and-program-performance.html