Skip to content

Instantly share code, notes, and snippets.

@deeplook
Last active May 28, 2019 19:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deeplook/f565a9618dd7bfe498cb1cd0aa7cec09 to your computer and use it in GitHub Desktop.
Save deeplook/f565a9618dd7bfe498cb1cd0aa7cec09 to your computer and use it in GitHub Desktop.
Benchmark using Fibonacci numbers with Python, Cython and PyPy.
#!/usr/bin/env bash
echo "Benchmark for Fibonacci numbers with Python3, Cython and PyPy"
echo '
def fib(n):
"Return the n-th Fibonacci number."
i = 0
a, b = 0, 1
if n < 2:
return [a, b][n]
while i < n:
a, b = b, a + b
i += 1
return a
' > pyfib.py
set -o xtrace
cat pyfib.py
cp pyfib.py cyfib.pyx
NUM=100000
python --version
python -m timeit -s "import pyfib" "pyfib.fib($NUM)"
python -c "import cython; print('Cython: %s' % cython.__version__)"
python -m timeit -s "import pyximport; pyximport.install(); import cyfib; import warnings; warnings.filterwarnings('ignore')" "cyfib.fib($NUM)"
pypy --version
pypy -m timeit -s "import pyfib" "pyfib.fib($NUM)"
set +o xtrace
@CTimmerman
Copy link

CTimmerman commented May 28, 2019

Sweet pyx oneliner, but the warning part seems moot, like the speedup without some annotations in your pyx.

"""
$ /mnt/c/Python36/python.exe -m timeit -s "import pyfib" "pyfib.fib(10000)"
1000 loops, best of 3: 1.82 msec per loop
$ /mnt/c/Python36/python.exe -m timeit -s "import pyximport; pyximport.install(); import cyfib_old" "cyfib_old.fib(10
000)"
1000 loops, best of 3: 1.41 msec per loop
$ /mnt/c/Python36/python.exe -m timeit -s "import pyximport; pyximport.install(); import cyfib" "cyfib.fib(10000)"
100000 loops, best of 3: 5.13 usec per loop
"""
def fib(int n):
    "Return the n-th Fibonacci number."
    cdef int i = 0
    cdef int a, b
    a, b = 0, 1
    if n < 2:
        return [a, b][n]
    while i < n:
        a, b = b, a + b
        i += 1
    return a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment