Liam的计组学习历程(二):对比程序运算时间(2015.10.20)

对比执行时间实验

机器规格: CPU型号:Intel Core i7-366U;

 

             CPU主频:2.0 GHz(最大睿频:3.2GHz);

 

               核心数: 双核心, 线程数:四线程;

 

               RAM :8GB;

 

               操作系统位数:64位。

 

在VS中编写代码如下:

#include "stdafx.h"
#include "iostream"
#include "windows.h"
#include "time.h"

using namespace std;

int src[2048][2048];
int dst[2048][2048];
SYSTEMTIME lpsystime;

void copyij(int src[2048][2048], int dst[2048][2048]);
void copyji(int src[2048][2048], int dst[2048][2048]);
void printTime();
int _tmain(int argc, _TCHAR* argv[])
{
    printTime();
    copyij(src,dst);
    printTime();
    copyji(src, dst);
    printTime();
    return 0;
}

void copyij(int src[2048][2048], int dst[2048][2048]){
    int i, j;
    for (i = 0; i < 2048; i++)
        for (j = 0; j < 2048; j++)
            dst[i][j] = src[i][j];
}

void copyji(int src[2048][2048], int dst[2048][2048]){
    int i, j;
    for (j = 0; j < 2048; j++)
        for (i = 0; i < 2048; i++)
            dst[i][j] = src[i][j];
}

void printTime(){
    GetLocalTime(&lpsystime);
    printf("%u:%u:%u:%u
",  lpsystime.wHour, lpsystime.wMinute, lpsystime.wSecond, lpsystime.wMilliseconds);
}

运行结果如下:

分析:

由结果我们可以计算出:先运行i后运行j的时间为16毫秒,先运行j后运行i的时间为203毫秒相差超过12倍。这个原因主要是因为先运行i后运行j时每一行i都被都进了告诉缓存中,读取可以快速处理,而如果先运行j再运行i,则需要每处理一项向缓存中存储一次,这要就大大增加了程序的处理时间,进而产生了上面的结果。

 

原文地址:https://www.cnblogs.com/tju-liuchang/p/4894331.html