C Language Register variable

Source: Internet
Author: User

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

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.