C语言速度优化之指针赋值与if推断

近期在写的一个项目须要优化处理速度,我写了一下程序来測试指针赋值与指针推断的速度比較。结果让我大吃一惊。

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 



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++
相同的。每次都訪问了指针指向的地址。结果赋值居然比推断快。

原文地址:https://www.cnblogs.com/yjbjingcha/p/7105966.html