4 ms·
FYI: pypy3 is 10x faster than CPython on this benchmark. ~> python fib.py 4825.7598876953125 ms ~> pypy3 fib.py 514.7459506988525 ms
by fermigier 6y ago
FYI: pypy3 is 10x faster than CPython on this benchmark.
~> python fib.py
4825.7598876953125 ms
~> pypy3 fib.py
514.7459506988525 ms
- fermigier 6y agoAlso, add a couple of type annotations to the program: import time def fib(n: int) -> int: if n == 1 or n == 0: return 1 return fib(n - 1) + fib(n - 2) t0 = time.time() fib(35) t1 = time.time() print(f"{(t1 - t0) \* 1000} ms") The run: ~> mypyc fib.py And boom: ~> python >>> import fib 332.64994621276855 ms (FYI, mypyc is a compiler that's part of the mypy package).
- Florin_Andrei 6y agothere's a backslash in the print statement that crashes it
- masklinn 6y agoWouldn't just straight running this through cython make more sense? Or numba?
- singhrac 6y agoWell, a point in mypyc’s favor is that the above code is still syntactically valid Python code.
- masklinn 6y agoBoth numba and cpython work with python code AFAIK. I don't know that cpython would take advantage of mypy annotations and you can make a cpython program not python-compatible, but you don't have to.
- williamstein 6y agoHere are some timings using three different approaches using Cython, and also numba: https://share.cocalc.com/share/df81e09e5b8f16f28b3a2e818dcdd4560e7818ae/support/2021-02-09-fib-cython.sagews?viewer=share https://share.cocalc.com/share/df81e09e5b8f16f28b3a2e818dcdd... Numba wins and is about twice as fast as my most clever Cython code. Naive Cython is pretty bad, but more clever Cython is reasonably good (though not as good as numba).
- PartiallyTyped 6y agoNumba version: @numba.jit def fib(n): if n == 1 or n == 0: return 1 return fib(n - 1) + fib(n - 2) first run: 498.46601486206055 ms. second run: 89.19310569763184 ms. For completeness, with njit: @numba.njit def fib(n): if n == 1 or n == 0: return 1 return fib(n - 1) + fib(n - 2) first run: 152.62889862060547 ms second run: 86.35592460632324 ms
- Florin_Andrei 6y agoWeird. On Mac I get 282 ms from pypy3, but 233 ms from numba. from numba import jit @jit def fib(n: int) -> int:
- PartiallyTyped 6y agoEven on subsequent runs?
- Florin_Andrei 6y agoYeah, that's the weird part.