15

I was messing around with the worst code I could write, (basicly trying to break things) and i noticed that this piece of code:

for(int i = 0; i < N; ++i)
    tan(tan(tan(tan(tan(tan(tan(tan(x++))))))));
end
std::cout << x;

where N is a global variable runs significantly slower then:

int N = 10000;
for(int i = 0; i < N; ++i)
    tan(tan(tan(tan(tan(tan(tan(tan(x++))))))));
end
std::cout << x;

What happens with a global variable that makes it run slower?

3
  • 1
    I suppose the compiler could suspect that x gets modified inside the tan function which prevents lots of optimization. I'm not sure that this happens here though.
    – Pubby
    Mar 5, 2013 at 5:15
  • @Pubby The only difference is the N deceleration though? Mar 5, 2013 at 5:17
  • well, if x is local then obviously it can't be modified inside tan. So declarations do matter.
    – Pubby
    Mar 5, 2013 at 5:19

5 Answers 5

12

tl;dr: Local version keeps N in a register, global version doesn't. Declare constants with const and it'll be faster no matter how you declare it.


Here's the example code I used:

#include <iostream>
#include <math.h>
void first(){
  int x=1;
  int N = 10000;
  for(int i = 0; i < N; ++i)
    tan(tan(tan(tan(tan(tan(tan(tan(x++))))))));
  std::cout << x;
}
int N=10000;
void second(){
  int x=1;
  for(int i = 0; i < N; ++i)
    tan(tan(tan(tan(tan(tan(tan(tan(x++))))))));
  std::cout << x;
}
int main(){
  first();
  second();
}

(named test.cpp).

To look at the assembler code generated I ran g++ -S test.cpp.

I got a huge file but with some smart searching (I searched for tan), I found what I wanted:

from the first function:

Ltmp2:
    movl    $1, -4(%rbp)
    movl    $10000, -8(%rbp) ; N is here !!!
    movl    $0, -12(%rbp)    ;initial value of i is here
    jmp LBB1_2       ;goto the 'for' code logic
LBB1_1:             ;the loop is this segment
    movl    -4(%rbp), %eax
    cvtsi2sd    %eax, %xmm0
    movl    -4(%rbp), %eax
    addl    $1, %eax
    movl    %eax, -4(%rbp)
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan        
    callq   _tan
    callq   _tan
    movl    -12(%rbp), %eax
    addl    $1, %eax
    movl    %eax, -12(%rbp) 
LBB1_2:
    movl    -12(%rbp), %eax ;value of n kept in register 
    movl    -8(%rbp), %ecx  
    cmpl    %ecx, %eax  ;comparing N and i here
    jl  LBB1_1      ;if less, then go into loop code
    movl    -4(%rbp), %eax

second function:

Ltmp13:
    movl    $1, -4(%rbp)    ;i
    movl    $0, -8(%rbp) 
    jmp LBB5_2
LBB5_1:             ;loop is here
    movl    -4(%rbp), %eax
    cvtsi2sd    %eax, %xmm0
    movl    -4(%rbp), %eax
    addl    $1, %eax
    movl    %eax, -4(%rbp)
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan
    callq   _tan
    movl    -8(%rbp), %eax
    addl    $1, %eax
    movl    %eax, -8(%rbp)
LBB5_2:
    movl    _N(%rip), %eax  ;loading N from globals at every iteration, instead of keeping it in a register
    movl    -8(%rbp), %ecx

So from the assembler code you can see (or not) that , in the local version, N is kept in a register during the entire calculation, whereas in the global version, N is reread from the global at each iteration.

I imagine the main reason why this happens is for things like threading, the compiler can't be sure that N isn't modified.

if you add a const to the declaration of N (const int N=10000), it'll be even faster than the local version though:

    movl    -8(%rbp), %eax
    addl    $1, %eax
    movl    %eax, -8(%rbp)
LBB5_2:
    movl    -8(%rbp), %eax
    cmpl    $9999, %eax ;9999 used instead of 10000 for some reason I do not know
    jle LBB5_1

N is replaced by a constant.

3
  • What do you get if you enable optimization when compiling that?
    – Mankarse
    Mar 5, 2013 at 5:51
  • 4
    Threading doesn't come in the the compiler's decision process, because race conditions are undefined behavior. N is loaded every iteration because the compiler can not be sure that tan does not modify N.
    – Mankarse
    Mar 5, 2013 at 6:04
  • That looks like a serious optimization failure: An unmodified and "unexposed" local variable like N can be treated as never modified after initialization, and hence replaced with a constant, even without const. Mar 5, 2013 at 15:04
9

The global version can't be optimized to put it in a register.

1
  • @Krishnabhadra: Not in this case. The thing is the compiler doesn't know nobody else is going to use it. Mar 5, 2013 at 5:21
8

I did a little experiment with the question and the answer of @rtpg,

experimenting with the question

In the file main1.h the global N variable

int N = 10000;

Then in the main1.c file, 1000 computations of the situation:

#include <stdio.h>
#include "sys/time.h"
#include "math.h"
#include "main1.h"



extern int N;

int main(){

        int k = 0;
        timeval static_start, static_stop;
        int x = 0;

        int y = 0;
        timeval start, stop;
        int M = 10000;

        while(k <= 1000){

                gettimeofday(&static_start, NULL);
                for (int i=0; i<N; ++i){
                        tan(tan(tan(tan(tan(tan(tan(tan(x++))))))));
                }
                gettimeofday(&static_stop, NULL);

                gettimeofday(&start, NULL);
                for (int j=0; j<M; ++j){
                        tan(tan(tan(tan(tan(tan(tan(tan(y++))))))));
                }
                gettimeofday(&stop, NULL);

                int first_interval = static_stop.tv_usec - static_start.tv_usec;
                int last_interval = stop.tv_usec - start.tv_usec;

                if(first_interval >=0 && last_interval >= 0){
                        printf("%d, %d\n", first_interval, last_interval);
                }

                k++;
        }

        return 0;
}

The results are shown in the follow histogram (frequency/microseconds) :

the histogram for the comparison output time in both methods The red boxes are the non global variable based ended for loop (N), and the transparent green the M ended based for loop (non global).

There are evidence to suspect that the extern global varialbe is a little slow.

experimenting with the answer The reason of @rtpg is very strong. In this sense, a global variable could be slower.

Speed of accessing local vs. global variables in gcc/g++ at different optimization levels

To test this premise i use a register global variable to test the performance. This was my main1.h with global variable

int N asm ("myN") = 10000;

The new results histogram:

Results with register global variable

conclusion there are performance improve when the global variable is in register. There is no a "global" or "local" variable problem. The performance depends on the access to the variable.

0
5

I'm assuming the optimizer doesn't know the contents of the tan function when compiling the above code.

Ie, what tan does is unknown -- all it knows is to stuff stuff onto the stack, jump to some address, then clean up the stack afterwards.

In the global variable case, the compiler doesn't know what tan does to N. In the local case, there are no "loose" pointers or references to N that tan could legitimately get at: so the compiler knows what values N will take.

The compiler can flatten the loop -- anywhere from completely (one flat block of 10000 lines), partially (100 length loop, each with 100 lines), or not at all (length 10000 loop of 1 line each), or anything in between.

The compiler knows way more when your variables are local, because when they are global it has very little knowledge about how they change, or who reads them. So few assumptions can be made.

Amusingly, this is also why it is hard for humans to reason about globals.

0

i think this may be a reason: Since Global variables are stored in heap memory,your code needs to access heap memory each time. May be because of above reason code runs slow.

1
  • global variables are stored in DATA segment of STACK and not in heap.
    – niko
    Oct 30, 2014 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.