yanyu
yanyu

Reputation: 227

Why with or without const Modifier make efficiency diff 4 times?

Why with or without const Modifier make efficiency diff 4 times? This code need about 16 second to finish in my PC. But if I make a small change, like declare mod as const int or move the mod declaration in the main body, or change i as int type, the execute time reduced to 4 second. (I compile this code use g++ with default parameters)

Here is the assembly code for this code, the left part is generate with non-const int mod, another with const int mod declaration.

The big efficiency occur only when I declare i as long long and the operator in for loop is '%'. Otherwise the performance only diff about 10%.

// const int mod = 1000000009; 
int mod = 1000000009; 

int main(){
    // int mod = 1000000009; 
    int rel = 0;
    for(long long i=1e9; i<2*(1e9); i++){
        rel = i % mod;
    }
    return 0;
}

Upvotes: 1

Views: 210

Answers (3)

zouxiaohang
zouxiaohang

Reputation: 21

Because when you add const,the compile changes it into the constant value and write it into the assemble codes, but when you do not add const, the value will be loaded into the register, so you must query it every time you have to use it

Upvotes: 2

barak manos
barak manos

Reputation: 30136

When loading the value of mod from memory into a register, the generated assembly code is different.

For example, this is what you get when using the Visual Studio 2013 compiler for x64 based processor:

For int mod = 1000000009:

mov  eax,dword ptr ds:[xxxxxxxxh]  ;  xxxxxxxxh = &mod
cdq
push edx
push eax

For const int mod = 1000000009:

push 0
push 3B9ACA09h  ;  3B9ACA09h = 1000000009

Upvotes: 1

Ajay
Ajay

Reputation: 18429

A const variable may or may not take space on stack - that's upto the compiler. But, in most cases, a const-variable's usage will be replaced by its constant value. Consider:

const int size = 100;

int* pModify = (int*)&size;
*pModify = 200;

int Array[size];

When you use *pModify it will render 200, but the size of array would be 100 elements only (ignore compiler extensions of new features that allow variable size arrays). It is just because compiler has replaced [size] with [100]. When you use size, it will mostly be just 100.

In that loop %mod is just getting replaced with %1000000009. There is one read-memory (load) instruction less, that's why it is performing fast.

But, it must be noted that compilers act smart, very smart, so you cannot guess what optimization technique it might have applied. It might have removed all of loop (since it seems no-op to the compiler).

Upvotes: 0

Related Questions