最近在写的一个项目需要优化处理速度,我写了一下程序来测试指针赋值与指针判断的速度比较。结果让我大吃一惊。
#include
#include
#include
int main(int argc, char *argv[]) {
int j;
int * tmp;
clock_t start = clock();
int i=0;
tmp=malloc(sizeof(int *));
for(;i<100000000;i++){
tmp[0]=2324;
tmp[1]=32423;
tmp[2]=90123;
tmp[3]=23421;
}
clock_t end = clock();
printf(程序运行时间为: %ld ms
,end - start);
start = clock();
i=0;
for(;i<100000000;i++){
if(tmp[0]==2356){
j=9089;
}
if(tmp[1]==234){
j=7812;
}
if(tmp[2]==2342){
j=2345;
}
if(tmp[3]==23423){
j=12032;
}
}
end = clock();
printf(程序运行时间为: %ld ms,end - start);
return 0;
}
结果如下:
程序运行时间为: 296 ms
程序运行时间为: 344 ms
我又运行了数次,结果都是前一段程序比后一段程序块40~50ms左右。猜测可能是因为我在for循环中一直赋同样的值,编译器做了相关优化,可是如果那样的,不可能只快40~50ms。
第一小部分的程序主体是:
for(;i<100000000;i++){
tmp[0]=2324;
tmp[1]=32423;
tmp[2]=90123;
tmp[3]=23421;
}
第一小部分的程序主体是:
for(;i<100000000;i++){
if(tmp[0]==2356){
j=9089;
}
if(tmp[1]==234){
j=7812;
}
if(tmp[2]==2342){
j=2345;
}
if(tmp[3]==23423){
j=12032;
}
}
测试环境是 :Dev C++
同样的,每次都访问了指针指向的地址,结果赋值竟然比判断快。