下面两个函数哪个更好一些
大家发表一下意见
1.
for (row=0; row<100; row++)
{
for ( col=0; col<5; col++ )
{
sum = sum + a[row][col];
}
}
2.
for (col=0; col<5; col++ )
{
for (row=0; row<100; row++)
{
sum = sum + a[row][col];
}
}
[解决办法]
2好,减少循环切换的次数
[解决办法]
第二个,CPU跨切循环层的次数少
[解决办法]
#include<stdio.h>#include<time.h>//here add other file need to included, and declare namespace need to use.#define ROWCOUNT 1000000#define COLCOUNT 50int array[ROWCOUNT][COLCOUNT];int sum;//here declare global variables;//here add funtions.int main(int argc, char* argv[]){ for(int i = 0; i < ROWCOUNT; ++i) for(int j= 0; j < COLCOUNT; ++j) sum += array[i][j]; clock_t time_elapsed = clock(); printf("%lf s.\n", (double)time_elapsed / CLOCKS_PER_SEC); time_elapsed = clock(); for(int i = 0; i < COLCOUNT; ++i) for(int j= 0; j < ROWCOUNT; ++j) sum += array[j][i]; clock_t time_elapsed1 = clock() - time_elapsed ; printf("%lf s.\n", (double)time_elapsed1 / CLOCKS_PER_SEC); return 0;}
[解决办法]
#include<stdio.h>
#define ROWCOUNT 1000000
#define COLCOUNT 50
int array[ROWCOUNT][COLCOUNT];
int sum;
void fun1()
{
for(int i = 0; i < ROWCOUNT; ++i)
for(int j= 0; j < COLCOUNT; ++j)
sum += array[i][j];
}
void fun2()
{
for(int i = 0; i < COLCOUNT; ++i)
for(int j= 0; j < ROWCOUNT; ++j)
sum += array[j][i];
}
int main(int argc, char* argv[])
{
fun1();
fun2();
return 0;
}
使用Profile测试结果为:
Func Func+Child Hit
Time % Time % Count Function
---------------------
2099.990 86.3 2099.990 86.3 1 fun2(void) (sfss.obj)
334.732 13.7 334.732 13.7 1 fun1(void) (sfss.obj)
0.000 0.0 2434.723 100.0 1 _main (sfss.obj)