参考“平凡的程序员”的博客文章,自己做了一定修改。
传送门http://blog.csdn.net/feixiaoxing/article/list/2
注意:我这里讨论的是ARM平台上的嵌入式C语言,与PC机上的运行结果有一定出入。其中有些结果是完全相反的。
编译环境:Fedora14 arm-linux-gcc 4.4.3
程序运行环境:mini2440 Linux2.6.32
编程规则1:二维数据先内层,再外层
理由:系统中二维数组采用行续优先的存储方式存储
main.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <netinet/in.h> int getTickCount() { struct timeval current; int currentTime; gettimeofday(¤t, NULL); currentTime = current.tv_sec * 1000000 + current.tv_usec; return currentTime; } int main() { int beginTime, endTime; int i, j; int data[1000][1000]; beginTime = getTickCount(); for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) data[i][j] = 12; endTime = getTickCount(); printf("duration = %d \n", endTime - beginTime); beginTime = getTickCount(); for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) data[j][i] = 12; endTime = getTickCount(); printf("duration = %d \n", endTime - beginTime); }
运行结果:
[root@ShiGuang /home]# ./arm-test duration = 131362 duration = 628395 [root@ShiGuang /home]#
编程规则2:尽量少使用乘除,多使用移位运算
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <netinet/in.h> int getTickCount() { struct timeval current; int currentTime; gettimeofday(¤t, NULL); currentTime = current.tv_sec * 1000000 + current.tv_usec; return currentTime; } int main() { int beginTime, endTime; int i, j; int data1 = 65536; int data2 = 65536; int result; beginTime = getTickCount(); for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) result = data1 / 16 + data2 * 4; endTime = getTickCount(); printf("duration = %d \n", endTime - beginTime); beginTime = getTickCount(); for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) result = data1 >> 4 + data2 << 2; endTime = getTickCount(); printf("duration = %d \n", endTime - beginTime); }
运行结果:
[root@ShiGuang /home]# ./arm-test duration = 62228 duration = 52170 [root@ShiGuang /home]#