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

前端 未结 2 1352
小蘑菇
小蘑菇 2020-12-30 03:48

I found that different compiler optimization levels in gcc give quite different results when accessing a local or a global variable in a loop. The reason this surprised me i

2条回答
  •  忘掉有多难
    2020-12-30 04:32

    Global variable = global memory, and subject to aliasing (read as: bad for the optimizer -- must read-modify-write in the worst case).

    Local variable = register (unless the compiler really can't help it, sometimes it must put it on the stack too, but the stack is practically guaranteed to be in L1)

    Accessing a register is on the order of a single cycle, accessing memory is on the order of 15-1000 cycles (depending on whether the cache line is in cache and not invalidated by another core, and depending on whether the page is in the TLB).

提交回复
热议问题