Pointer assignment and if judgment for C language Speed Optimization

Source: Internet
Author: User

Pointer assignment and if judgment for C language Speed Optimization

A recently written project needs to optimize the processing speed. I wrote a program to test the speed of pointer assignment and pointer judgment. The results surprised me.

# 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 (program running time: % 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 (Program runtime: % ld MS, end-start ); return 0 ;}
    
   
  

The result is as follows:

Run Time: 296 ms run time: 344 ms

I ran it several times and the result was that the previous program was 40 ~ About 50 ms. I guess it may be because I have always assigned the same value in the for loop, and the compiler has done some optimization. However, if that is the case, it cannot be as fast as 40 ~ 50 ms.
The main body of the first part of the program is:

 for(;i<100000000;i++){        tmp[0]=2324;        tmp[1]=32423;        tmp[2]=90123;        tmp[3]=23421;    }

The main body of the first part of the program is:

    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;     }    }

Test environment: Dev C ++
Similarly, every time a pointer is directed to the address, the result assignment is faster than the judgment.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.