Why Calculating Small Fibonacci Sequence With Python Interpreter Faster Than PyPy
Solution 1:
In addition to the other answer(s): your fibonacci example would run at roughly the same speed if it was written in C, C#, in Python with or without a JIT, or anywhere else. That's because the fibonacci example makes exponentially large numbers. After a few iterations it is spending all the time inside the library handling ever larger integers, and almost none outside it.
Of course we can discuss the finer points of why it is a bit faster or slower in this or this case, but that's comparing small constant overheads and details of the long-integer libraries used; it has little to do with the language.
Solution 2:
The pypy JIT needs a little bit of time to initialize and will work better with repeat results. To illustrate with a slightly different version of the code:
from __future__ import print_function
import sys
from datetime import datetime
def fibonacci(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a + b
return a
n = int(sys.argv[1])
runs = int(sys.argv[2])
durations = []
for i in range(runs):
start = datetime.now()
fibonacci(int(n))
durations.append(datetime.now() - start)
durations.sort()
print('min:', durations[0])
print('median:', durations[int(runs / 2)])
print('max:', durations[-1])
And running it on a few Python versions:
# python2 --version
Python 2.7.18rc1
# python2 fib.py 5000 1000
min: 0:00:00.000303
median: 0:00:00.000307
max: 0:00:00.001273
# python2 fib.py 1000000 5
min: 0:00:05.711701
median: 0:00:05.782151
max: 0:00:05.850577
# python3 --version
Python 3.8.2
# python3 fib.py 5000 1000
min: 0:00:00.000305
median: 0:00:00.000309
max: 0:00:00.001254
# python3 fib.py 1000000 5
min: 0:00:05.796954
median: 0:00:05.825557
max: 0:00:05.841489
# pypy --version
Python 2.7.13 (7.3.1+dfsg-2, Apr 21 2020, 05:05:41)
[PyPy 7.3.1 with GCC 9.3.0]
# pypy fib.py 5000 1000
min: 0:00:00.000160
median: 0:00:00.000179
max: 0:00:00.002456
# pypy fib.py 1000000 5
min: 0:00:04.314290
median: 0:00:04.405727
max: 0:00:04.453215
Post a Comment for "Why Calculating Small Fibonacci Sequence With Python Interpreter Faster Than PyPy"