I wrote a simple factorial function and tested its performance. But surprisingly my function is faster than math.factorial. Why it might happen? Am I doing everything correct?
Changing the return and argument data type to long long
, also fast.
Cpp code:
#include "fact.hpp"
int fact(int n) {
if (n<=1) {
return 1;
}
return n*fact(n-1);
}
My test python script is given bellow. Cpp binding is done using Cython.
import cython_fact
import timeit
setup1 = """
def fact(n):
s = 1
for i in range(1, n+1):
s*=i
return s
"""
code1 = """
fact(50)
"""
setup2 = """
from cython_fact import factorial
"""
code2 = """
factorial(50)
"""
setup3 = """
from math import factorial
"""
code3 = """
factorial(50)
"""
print(timeit.timeit(stmt=code1, setup=setup1))
print(timeit.timeit(stmt=code2, setup=setup2))
print(timeit.timeit(stmt=code3, setup=setup3))
Outputs:
1.555461709
0.01813229099999991
0.20942320800000003
EDIT: Had some silly mistake in factorial calculation.