Skip to content Skip to sidebar Skip to footer

Why Calculating Small Fibonacci Sequence With Python Interpreter Faster Than Pypy

I was making some fibonacci calculations with PyPy, first i started with bigger numbers, PyPy was a little bit faster, but with small numbers it gives nearly the same performance a

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


deffibonacci(n):
    a, b = 0, 1for i inrange(0, n):
        a, b = b, a + b
    return a

n = int(sys.argv[1])
runs = int(sys.argv[2])
durations = []
for i inrange(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 --versionPython2.7.18rc1# python2 fib.py 5000 1000min:0:00:00.000303median:0:00:00.000307max:0:00:00.001273# python2 fib.py 1000000 5min:0:00:05.711701median:0:00:05.782151max:0:00:05.850577# python3 --versionPython3.8.2# python3 fib.py 5000 1000min:0:00:00.000305median:0:00:00.000309max:0:00:00.001254# python3 fib.py 1000000 5min:0:00:05.796954median:0:00:05.825557max:0:00:05.841489# pypy --versionPython2.7.13(7.3.1+dfsg-2,Apr212020,05:05:41)
[PyPy7.3.1withGCC9.3.0]
# pypy fib.py 5000 1000min:0:00:00.000160median:0:00:00.000179max:0:00:00.002456# pypy fib.py 1000000 5min:0:00:04.314290median:0:00:04.405727max:0:00:04.453215

Post a Comment for "Why Calculating Small Fibonacci Sequence With Python Interpreter Faster Than Pypy"