samedi 25 avril 2015

GCC optimization of iterative functions

I have the following code for Fibonacci both for recursive and iterative versions:

#include <stdio.h>

typedef long long INT;

long long recursive (long long i) {
    if (i == 0) return 0;
    if (i == 1) return 1;
    return recursive (i-1) + recursive (i-2);
}


long long iterative (long long i) {
    INT counter = i-1;
    INT fib1 = 0;
    INT fib2 = 0;

    // first iteration
    fib1 = 0;
    fib2 = 1;

    while (counter > 0) {
        INT temp1 = fib1;
        INT temp2 = fib2;
        fib1 = fib2;
        fib2 = temp1 + temp2;

        counter--;
    }

}

int main (int argc, char **argv) {

    printf("Result: %lli\n", iterative(10));

    return 0;
}

I tried compiling it with GCC -O2 optimization to see if recursion would perform better than iteration, but I noticed an interesting occurrence: when compiled with -O2, the iterative function outputs 0 while if it's compiled without the flag, it outputs the proper number.

gcc -O2 fibonacci.c -o fib && ./fib: Result: 0

gcc fibonacci.c -o fib && ./fib: Result: 55

Aucun commentaire:

Enregistrer un commentaire