Registers exist inside the CPU and are computationally fast because the data in memory must be loaded into registers to be counted. If you define a variable as a register variable directly, the process of loading is less fast. For frequently used variables, you can put it in registers to raise the speed.
For the VC compiler is automatically optimized, even if the register variable is not declared, the VC will be automatically optimized.
It is not automatically optimized for the GCC compiler.
Define a Register variable:
2 3 void Main () 4 {5 int 0 ; 6 // // register variable placed in CPU, no address, but no problem in C + + 7 }
Next, compile the following code through the GCC compiler to test the execution speed.
1#include <stdio.h>2#include <stdlib.h>3#include <time.h>4 5 voidmain4 ()6 {7 time_t start,end;8Time (&start);//gets the current time, placed in the start variable9 Ten //here is the GCC compiler, which is not automatically optimized here. One //the test does not set the register variable, it takes 8 seconds for the program to run A //double res = 0.0;//Results - //long int i = 0; - the //Defining a register variable, which takes only 4-5 seconds to execute, is much more efficient. -RegisterDoubleres =0.0; -RegisterLong inti =0; - + for(;i<2500000000; i++) - { +Res + =i; A } atprintf"%f\n", res); - -Time (&end);//Gets the current time placed in end - -printf"%d", (unsignedint) (End-start));//Get time difference -}
The above code can conclude that for frequently used variables it is possible to prefix it with the keyword register, which is defined as a register variable.
Finally, it is worth noting the following 2 points:
1 // Global variables are best not to occupy registers, which can affect the speed of the program 2 int + ; 3 4 // Static variables cannot be defined as register variables, static variables exist in static zones 5 Static Double 0.0;
C Language Register variable