IT Engineer, coder, dreamer.


An in-the-small look into GCC optimizations

The purpose of this brief article is to illustrate how GNU GCC handles optimizations flags (-O0, -O1, -O2, -O3, -O4) by looking at the assembler code it produces for simple mathematical functions.

I chose to keep things simple: so no printf, no I/O, no real function calls.

My GCC version: gcc (GCC) 4.5.2 20110127 (prerelease)

Platform: Linux x86_64

Here's the code used for testing:

#include <math.h>

// Compile with gcc -S and -O0, -O1, -O2 ...

unsigned int multiply(unsigned int a, unsigned int b) {
        return (unsigned int) a*b;
}

unsigned int half(unsigned int x) {
        return (unsigned int) x/2;
}

unsigned int twice(unsigned int x) {
        return (unsigned int) x*2;
}

float radice(float x) {
        return sqrt(x);
}

int main() {
        return 0;
}

Optimizations >= -O2 returned the exact same ASM.