c - GCC optimization of iterative functions -
i have following code fibonacci both recursive , 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 gcc -o2
optimization see if recursion perform better iteration, noticed interesting occurrence: when compiled -o2
, iterative function outputs 0 while if it's compiled without flag, outputs proper number.
gcc -o2 fibonacci.c -o fib && ./fib
: result: 0
gcc fibonacci.c -o fib && ./fib
: result: 55
recursion slower iterative or tail recursion version (which gets optimized iterative version). examples of both in thread:
Comments
Post a Comment