这是一个适当的循环优化 [英] Is this a proper for-loop optimization
问题描述
为了做家庭作业,我需要优化一个循环,在7.5秒内运行。我想我可能已经这样做了,因为我的代码在4秒内运行。不过,我担心我做得不对,因为我的老师告诉我们,7.5秒以下的事情可能是错误的。所以我担心我可能不会正确地做事。这里是原始代码:
#include< stdio.h>
)的
#include< stdlib.h>
#define N_TIMES 600000 $ b $ #define ARRAY_SIZE 10000
$ b $ int main(void)
{
double * array = calloc(ARRAY_SIZE,的sizeof(双));
double sum = 0;
int i;
for(i = 0; i
int j; (j = 0; jsum + = array [j];
;
}
}
return 0;
$ / code $
这里是我的优化:
$ b $ (i = 0; i
int j; b(j = 0; j
sum + = array [j] + array [j + 1] + array [j + 2] + array [j + 3] + array [j + 4] + array [j + 5] + array [j + 6] + array [j + 7] + array [ ]。
sum1 + = array [j + 10] + array [j + 11] + array [j + 12] + array [j + 13] + array [j + 14] + array [j + 15] + array [j + 16] + array [j + 17] + array [j + 18] + array [j + 19];
}
}
sum + = sum1;
这些算术运算的数目是否相同?我是否改变了代码,或者我只是优化?
解决方案您的优化是不正确的:
$ b (j = 0; j
$ bpre>
您现在循环内循环的次数是您应该循环的次数的一半。
For a homework assignment I need to optimize a loop to run in under 7.5 seconds. I think I may have done this because my code runs in 4 seconds. However, I am worried I am not doing it correctly because my instructor told us that anything too far under 7.5 seconds is probably wrong. So I am worried that I might not be doing things correctly. Here is the original code:
#include <stdio.h> #include <stdlib.h> #define N_TIMES 600000 #define ARRAY_SIZE 10000 int main (void) { double *array = calloc(ARRAY_SIZE, sizeof(double)); double sum = 0; int i; for (i = 0; i < N_TIMES; i++) { int j; for (j = 0; j < ARRAY_SIZE; j++) { sum += array[j]; } } return 0; }
Here is my optimization:
for (i = 0; i < N_TIMES; i++) { int j; for (j = 0; j < ARRAY_SIZE/2; j += 20) { sum += array[j] + array[j+1] + array[j+2] + array[j+3] + array[j+4] + array[j+5] + array[j+6] + array[j+7] + array[j+8] + array[j+9]; sum1 += array[j+10] + array[j+11] + array[j+12] + array[j+13] + array[j+14] + array[j+15] + array[j+16] + array[j+17] + array[j+18] + array[j+19]; } } sum += sum1;
Are these doing the same number of arithmetic operations? Did I change the code somehow or am I just optimizing well?
解决方案Your optimizations are not correct:
for (j = 0; j < ARRAY_SIZE/2; j += 20) {
You now loop half as many times in the inner loop as you should.
这篇关于这是一个适当的循环优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!