user763305 user763305 - 2 months ago 28
C++ Question

Visual Studio C++ compiler options: Why does /O2 define /Gs?

The Visual Studio C++ compiler option /O2 (maximize speed) is equivalent to

/Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy

Why /Gs? How does it help maximize speed? (Note that it is /Gs, not /GS.)


/Gs will insert stack probes in functions that use more than one page (4kB typically) of local variables. A stack probe signals to the OS that you'll use a lot of stack space. If this probe hits the guard page, the OS knows that it will need to allocate an extra page of RAM for the stack to grow.

This is an optimization, because without the probe the actual memory access would trigger the RAM allocation, and the function would stall until the RAM is allocated. The probe, as part of the function prolog, doesn't cause a stall (at least not as severe).

[edit] Another benefit is that a stack probe up front will allocate memory once. If you need 16 KB of stack space and rely on allocation-on-demand, you'll have 4 page faults that each grow the stack by 4 KB. A single probe can replace these 4 faults with one syscall.