c++performanceassemblycpu-registers

How to force c++ compiler to use registers?


I have a for loop in my (c++ .Net Win32 Console) code which has to run as fast as possible. So I need to make the compiler use a register instead of storing it in RAM.

MSDN says:

The register keyword specifies that the variable is to be stored in a machine register, if possible.

This is what I tried:

for(register int i = 0; i < Size; i++)

When I look at Disassembly code which the compiler generates, I see:

012D4484  mov         esi,dword ptr [std::_Facetptr<std::codecvt<char,char,int> >::_Psave+24h (12DC5E4h)]  
012D448A  xor         ecx,ecx  
012D448C  push        edi  
012D448D  mov         edi,dword ptr [std::_Facetptr<std::codecvt<char,char,int> >::_Psave+10h (12DC5D0h)]  
012D4493  mov         dword ptr [Size],ebx  
012D4496  test        ebx,ebx  
012D4498  jle         FindBestAdd+48h (12D44B8h)  //FindBestAdd is the function the loop is in
012D449A  lea         ebx,[ebx]  

I am expecting the assembly code not to generate a dword ptr where I used register keyword.

So, How would I know if it's possible for compiler to use a register and What should I do to force the compiler to read/write directly from/to registers.


Solution

  • In your case the compiler will most likely use a register anyway if you supply the right optimization options.

    In general, the only way to force a variable into a register is to use inline assembly.