See the article https://blog.csdn.net/qq_34827674/article/details/109147330 , write a program to test it.
1. Improve the hit rate of the data cache (traversing a two-dimensional array), which seems to be correct.
2. Improve the hit rate of the instruction cache (loop through the array, set the array elements less than 50 to 0; sort the array). For unknown reasons, the test results did not improve the speed.
The procedure is as follows:
#include "stdio.h"
#include <time.h>
#include <sys/time.h>
#include <algorithm>
using namespace std;
#define N 1000
#define N1 10000
int main(void)
{
struct timeval tpstart;
struct timeval tpend;
int array[N][N];
int i,j;
gettimeofday(&tpstart,NULL);
for(i=0; i < N; i++)
{
for(j=0; j < N; j++)
{
array[i][j] = 1;
}
}
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
gettimeofday(&tpstart,NULL);
for(i=0; i < N; i++)
{
for(j=0; j < N; j++)
{
array[j][i] = 1;
}
}
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
gettimeofday(&tpstart,NULL);
for(i=0; i < N; i++)
{
for(j=0; j < N; j++)
{
array[i][j] = 1;
}
}
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
gettimeofday(&tpstart,NULL);
for(i=0; i < N; i++)
{
for(j=0; j < N; j++)
{
array[i][j] = 1;
}
}
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
int array1[N1];
printf("\n");
for(i=0; i<N1; i++)
{
array1[i]=rand()%100;
//printf("%d ",array1[i]);
}
printf("\n");
gettimeofday(&tpstart,NULL);
for(i=0; i<N1; i++)
{
if(array1[i]<50)
{
array1[i]=0;
}
}
sort(array1,array1+N1);
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
//printf("\n");
//for(i=0; i<N1; i++)
//{
//printf("%d ",array1[i]);
//}
//printf("\n");
printf("\n");
for(i=0; i<N1; i++)
{
array1[i]=rand()%100;
//printf("%d ",array1[i]);
}
printf("\n");
gettimeofday(&tpstart,NULL);
sort(array1,array1+N1);
for(i=0; i<N1; i++)
{
if(array1[i]<50)
{
array1[i]=0;
}
}
gettimeofday(&tpend,NULL);
printf("time:%lds,%ldms\n", tpend.tv_sec-tpstart.tv_sec, tpend.tv_usec-tpstart.tv_usec);
//for(i=0; i<N1; i++)
//{
//printf("%d ",array1[i]);
//}
//printf("\n");
return 0;
}
Compile and run with g++, the result:
the first time
time:0s,21539ms
time:0s,93967ms
time:0s,16531ms
time:0s,16554ms
time:0s,6204ms
time:0s,6070ms
the second time
time:0s,21348ms
time:0s,94609ms
time:0s,16356ms
time:0s,16607ms
time:0s,6203ms
time:0s,6081ms