take a look at these two programs, the first is in CPython3 and the second one is C++17
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == "__main__":
n = 46
print(fibonacci(n))
#include <bits/stdc++.h>
using namespace std;
int fib( int n)
{
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 46;
cout << fib(n);
getchar ();
return 0;
}
so I benchmarked them and not to my suprise it took python 0.9 seconds to finish the program and it took 11 second for C++ to complete.
which is undestandable since C++ is like a big panel with a lot of different functions and buttons so if you write the code as I did and don’t consider optimizations like tail-recursion. you’re done for, which makes it a bad programming choice for novice programmers.
but I want to apply the option that python automatically grants at compile time. I call it algorithmic optimization
if you didn’t know to compile a c/cpp source you usually run it with optimization arguments such as O2 the most favored:
g++ fib.cpp -O2 -o fib.exe
now I want to change it like this:
g++ fib.cpp -Oa -o fib.exe
g++ fib.cpp -O2a -o fib.exe
but I don’t know at which point cpython does these optimizatios (when its compiled to bytecode or when it is interpreted etc.)
so I thought instead of going through cpython’s massive repo head on first I raise the question here.
after all as a rule of thumb in clean coding is not to rewrite a code that’s already written. so I believe in writing it from zero UNLESS I REALLY HAVE TO. but I can translate back what cpython’s community has done and commit it to gcc or llvm.
if it comes to fruition novice programmers will also be able to get a kick out of C++ and learning curve won’t be that high, until the point they learn how to write a fibonacci that executes in less than 0.9 seconds.C/CPP being compiled languages and all that.