问题5

来源:互联网 发布:dijkstra算法优先队列 编辑:程序博客网 时间:2024/04/30 08:08
// test5.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<windows.h>#include<cstdio>void f(){int a[10][10];for(int i=0; i<10; i++)for(int j=0; j<10; j++)a[i][j] = 0;}void g(){int a[10][10];for(int i=0; i<10; i++)for(int j=0; j<10; j++)a[j][i] = 0;}int main(){DWORD t1  = ::GetTickCount();for(int i = 0; i<1000000; i++)g();DWORD t2  = ::GetTickCount();printf("%d\n",t1);printf("%d\n",t2);DWORD t3  = ::GetTickCount();for(int i = 0; i<10; i++)f();DWORD t4  = ::GetTickCount();printf("%d\n",t3);printf("%d\n",t4);   //printf("%d\n",t1);getchar();return 0;}

运行结果差异很大

7250614

7251675

7251675

7251675

 

上面的例子 说明了一个问题:

L1和L2 cache(一级缓存和二级缓存)位于cpu和内存之间
访问速度快于内存,但慢于寄存器
内存存取采用了局部性原理:
当访问某一处内存地址时,下次再访问该地址及附近区域的概率较大
因此,当程序访问某个地址时,该地址连同之后的某个大小的内存空间的数据,都会被读入到cache中
下次访问内存中某个地址时,会首先检查cache中是否有该地址的数据,若有就没有必要再访问内存了。速度大大提高。

C/C++多维数组,先行后列遍历效率高

 

影响效率的实际上主要是大型数组导致的内存页面交换次数和cache命中率的高低,而不是循环次数本身。
在C++中,二维数组以先行后列的顺序存储在连续的内存中。
运行环境:VC++6.0
例子程序:test.cpp
***********************************************************************
#include <stdio.h>
#include <string.h>
#include <Windows.h>
#define MAX_ROW  10000
#define MAX_COLUMN  500
int main()
{
   
    int (*array)[MAX_COLUMN] = new int[MAX_ROW][MAX_COLUMN];
    DWORD startTime;
    DWORD endTime;
    startTime = GetTickCount();
    for (int i=0;i<MAX_ROW;i++ )
    {
        for (int j=0;j<MAX_COLUMN;j++)
        {
            array[i][j] = 1;
        }
       
    }
    endTime = GetTickCount();
   
    printf("先行后列,时间间隔: %d ms \n",endTime-startTime);
   
    startTime = GetTickCount();
    for (int m=0;m<MAX_COLUMN;m++ )
    {
        for (int n=0;n<MAX_ROW;n++)
        {
            array[n][m] = 2;
        }
       
    }
    endTime = GetTickCount();
   
    printf("先列后行,时间间隔: %d ms \n",endTime-startTime);

    return 0;
}


经过验证 在vs2008当中 栈空间也是接近1G的,但是不够

所以说二维数组int  1000*1000绝对开不得

1000*100还是可以的

原创粉丝点击