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.