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

  • 相关阅读:
    mysql常用指令
    mysql数据库文件简介和应用
    redis配置参数简介
    shell输入输出重定向
    memcached添加日志输出
    java 随机数种子
    统计学习方法——第四章朴素贝叶斯及c++实现
    统计学习方法——第二章的c++实现
    python函数带不带括号的问题
    numpy中的range()
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/7105966.html
Copyright © 2011-2022 走看看