Skip to content

Commit

Permalink
Show results also with better algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
jussienko committed Jan 24, 2020
1 parent 1fb394b commit 3e4b8cb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 8 additions & 0 deletions cython/c-functions/solution/fib_py.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
from functools import lru_cache

def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)

@lru_cache(maxsize=None)
def fibonacci_cached(n):
if n < 2:
return n
return fibonacci_cached(n-2) + fibonacci_cached(n-1)
15 changes: 11 additions & 4 deletions cython/c-functions/solution/test_fib.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from fib import fibonacci
from fib_py import fibonacci as fibonacci_py
from fib_py import fibonacci as fibonacci_py, fibonacci_cached
from timeit import repeat

ncython = 100
npython = 10
ncached = 10000000

# Pure Python
time_python = repeat("fibonacci_py(30)", number=npython, globals=locals())
Expand All @@ -13,7 +14,13 @@
time_cython = repeat("fibonacci(30)", number=ncython, globals=locals())
time_cython = min(time_cython) / ncython

print("Pure Python: {:5.4f} s".format(time_python))
print("Cython: {:5.4f} s".format(time_cython))
print("Speedup: {:5.1f}".format(time_python / time_cython))
# Python, cached
time_cached = repeat("fibonacci_cached(30)", number=ncached, globals=locals())
time_cached = min(time_cached) / ncached

print("Pure Python: {:5.4f} s".format(time_python))
print("Cython: {:5.4f} ms".format(time_cython*1.e3))
print("Speedup: {:5.1f}".format(time_python / time_cython))
print("Pure Python cached: {:5.4f} us".format(time_cached*1.e6))
print("Speedup over Cython: {:5.1e}".format(time_cython / time_cached))

0 comments on commit 3e4b8cb

Please sign in to comment.