CPU缓存机制对遍历二维数组效率的影响

  • 遍历二维数组的效率,跟CPU的缓存机制有关,步长之内的有缓存,可以直接读取缓存而不必和内存进行交换。

  • 因此,行遍历比列遍历有优势,行遍历是连续的内存块,可以一次读取入缓存,提高CPU的命中率。

#include "stdafx.h"
#include 
#include 
#include 
using namespace std;
int main()
{ 
 const int MAX_ROW=2000;
 const int MAX_COL=2000;
 int (*a)[MAX_COL]=new int[MAX_ROW][MAX_COL];
 clock_t start,finish;

 //先行后列
   start=clock();
   for(int i=0;ifor(int j=0;j1;
   finish=clock();
   //totaltime=(double)()/CLOCKS_PER_SEC;
   cout<<"先行后列遍历时间为:"<"ms"<//先列后行
   start=clock();
   for(int i=0;ifor(int j=0;j1;
   finish=clock();
   //totaltime=(double)()/CLOCKS_PER_SEC;
   cout<<"先列后行遍历时间为:"<"ms"<return 0;
}

你可能感兴趣的:(OS,Coding,二维数组,缓存机制,cpu)