C++写的对比不同数组遍历方式对程序执行时间的影响

 

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int a[20000][20000];//此处选择的数组大小是20000.经测试,如果是50000的话,会提示溢出错误 
int c[5][5];
//遍历数组A,采用先访问行再访问列的方式
void fun_1()
{    
    int i,j;    
   
    for(i=0; i<20000; i++)    
    {
	for(j=0; j<20000; j++)
	{
	    a[i][j]=i;
	}    
    }
}

//显示一下数组元素的地址,验证是否是按行存储。 
void fun_add()
{    
    int i,j;    
   
    for(i=0; i<5; i++)    
    {
	for(j=0; j<5; j++)
	{
	    c[i][j]=i;
	    cout<<"The address of c["<<i<<"]["<<j<<"] = "<< &c[i][j]<<endl ;
	}    
    }
}

//遍历数组A,采用先访问列再访问行的方式
void fun_2()
{    
    int i,j;  
    
    for(j=0; j<20000; j++)    
    {
	for(i=0; i<20000; i++)
	{
	    a[i][j]=i;
	}    
    }
}

int main()
{
    clock_t start, finish;
    double  duration;

    start = clock();
    fun_1();
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
   cout<<"The time for fun_1 is:"<<duration<<" seconds"<<endl;

    start = clock();
    fun_2();
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
    cout<<"The time for fun_2 is:"<<duration<<" seconds"<<endl;
    
    fun_add(); 
	
    return 0;
}

测试用电脑:Dell Inspiron 5370(16GB内存),windows 10

编译软件:Dev-C++ 5.311

运行结果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章