某型CPU的一级数据缓存大小为16K字节,cache块大小为64字节;二级缓存大小为256K字节,cache块大小为4K字节,采用二路组相联。经测试,下面两段代码运行时效率差别很大,请分析哪段代码更好,以及可能的原因。 为了进一步提高效率,你还可以采取什么办法 A段代码。 int matrix[1023][15]; const char *str = "this is a str"; int i, j, tmp, sum = 0; tmp = strlen(str); for(i = 0; i < 1023; i++) { for(j = 0; j < 15; j++) { sum += matrix[j] + tmp; } } B段代码 int matrix[1025][17]; const char *str = "this is a str"; int i, j, sum = 0; for(i = 0; i < 17; i++) { for(j = 0; j < 1025; j++) { sum += matrix[j] + strlen(str); } }
A代码远比B代码好:
1.B代码每次都要调用strlen()函数,这是个严重问题,属于逻辑级错误。
2.同样是逻辑错误,两串代码for循环执行顺序不同,A段代码中的循环执行语句对内存的访问是连续的,而B段代码中的循环执行语句对内存的访问是跳跃的。直接降低了B代码的运行效率。
3.B段代码犯了一个Cache级的错误,参考http://rednaxelafx.iteye.com/blog/412560
还可以使用如下代码提高效率
#define XX 15 #define YY 1023 int
matrix[XX][YY]; const char *str = "this is a str";
int i, j, tmp, sum = 0; tmp = strlen(str); for(i = 0; i <
XX; i++) for(j = 0; j < YY; j++) sum +=
matrix[i][j] + tmp;