求助:用并行计算知识解释同一数组操作的不同速度
对于数组操作a = a *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 = a * 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 = a * 2;
}
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds\n", duration );
}
free(a);
}
代码一是 4000000次循环时间
代码二将近4000000*20次循环时间
你说呢 然后测试代码运行时间用要求要更加精确最好
#include<stdio.h>
#include<math.h>
#include<windows.h>
#define N 200001
int main(int argc,char ** argv)
{
LARGE_INTEGER time,time2,ftp;
int prime = { 0 };
int i,j,t = 200;
QueryPerformanceFrequency(&ftp);
QueryPerformanceCounter(&time);
for (i = 3; i < N; i = i + 2)
{
prime = 1;
}
for (i = 3; i < sqrt(N); i = i + 2)
{
if (prime)
{
for (j = i+i; j < N; j += i)
{
prime = 0;
}
}
}
QueryPerformanceCounter(&time2);
printf("%d微秒\n",time2.QuadPart - time.QuadPart);
return 0;
}
注意不要debug 要release
页:
[1]