int i;for (i=0; i<1000; i++) { //Some Code}
In order to solve this problem, it is possible to put frequently used variables in the general register of the CPU, so that the use of the variable without access to memory, directly from the register to read, greatly improve the efficiency of the program operation.
To deepen the understanding of register variables, it is necessary to speak about CPU registers.
Registers are closest to the CPU, and the CPU is accessed only in registers. Storage means that the data is stored temporarily, not every time it is taken from memory, it is a temporary
Space for storing data.
So why do we need to cache it? Because if you frequently manipulate the data on the same address in memory, it can affect the speed, so you set a slow between the register and the memory
Storage, storing frequently used data to the cache, and if the register needs to read data from the same address in memory, it does not have to go all the way to access the memory, directly
Read from the cache.
Note: The capacity of the cache is limited, the registers can only be read from the cache to some of the data, for the use of less frequent data, will bypass the cache, directly into memory
Read. So not every time you can get the data from the cache, this is the cache hit rate, can be read from the cache hit, or die.
register variable
For an example that calculates the approximate value of π, an approximate formula for the solution is as follows:
To improve accuracy, the more loops the better, you can define the loop's increment control as a register variable, as follows:
#include <stdio.h> #include <conio.h>int main () { Register int i = 0; Register variable Double sign = 1.0, res = 0, ad = 1.0; for (I=1; i<=100000000; i++) { res + = AD; Sign=-sign; ad=sign/(2*i+1); } Res *= 4; printf ("Pi is%f", res); Getch (); return 0;}
There are several things to note about register variables:
1) assigning registers to register variables is done dynamically, so only local variables and formal parameters can be defined as register variables.
3) The length of the register is generally consistent with the machine's word size, so only shorter types such as int, char, short, etc., are suitable for the definition of a register variable, such as a large type such as double, it is not recommended to define it as a register type.
4) The number of registers for the CPU is limited, so even if a register variable is defined, the compiler may not really allocate a register for it, but instead treats it as a normal auto variable and allocates stack memory to it. Of course, some excellent compilers can automatically identify the use of frequent variables, such as cyclic control variables, when there are available registers, even if the Register keyword is not used, it will automatically assign a register, do not need to be specified by the programmer.
What is the meaning of a variable of register type in C language