|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
对于数组操作a[i] = a[i] *2,执行4百万次,为什么换了操作间距,程序速度相差会很大?
比如这是常规:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
clock_t start, finish;
double duration;
int * a = malloc(4000000*sizeof(int));
int i;
start = clock();
for ( i = 1; i <= 4000000; i++)
{
a[i] = a[i] * 2;
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds\n", duration );
free(a);
}
然后间隔20个来执行:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
clock_t start, finish;
double duration;
int * a = malloc(4000000*sizeof(int));
int i,j,k;
for (j=0; j < 10; j++)
{
start = clock();
for (k = 0; k < 20 ; k++)
{
for ( i = k; i < 4000000; i += 20)
{
a[i] = a[i] * 2;
}
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds\n", duration );
}
free(a);
}
|
|