1

The following code is used to calculate the fibonacci number:

# test.py
import time

def fib(n):
    a, b = 0, 1
    while True:
        if n == 0:
            return a
        if n == 1:
            return b
        n -= 1
        a, b = b, a + b

start = time.time()
result = fib(500000)
print('Time elapsed:', time.time() - start)

When I run the code above both by pypy and python, I get an unexpected result: pypy runs the code slower than python. It's strange!

The following is the screenshot of the comparing result:

screenshot

To check whether it's related to the different python versions or not, I run the following code again by pypy and python:

# test2.py
import time

start = time.time()
sum = 0
for i in range(10 ** 8):
    if i & 1:
        sum += i
print('Time elapsed:', time.time() - start)

The result of running is expected as the screenshot shows: pypy runs faster.

screenshot

My question is: is there anything special in test.py that makes pypy run slower?

The following is my CPU info:

Caption : Intel64 Family 6 Model 23 Stepping 10

DeviceID : CPU0

Manufacturer : GenuineIntel

MaxClockSpeed : 2801

Name : Intel(R) Core(TM)2 Duo CPU P9700 @ 2.80GHz

SocketDesignation : U2E1

Z-Y.L
  • 1,740
  • 1
  • 11
  • 15
  • @BenoîtZu If I understand it right, the result above is related to the cost of pypy's JIT. When I run the code only once, the time costed by pypy includes the time of JIT compiling, which cause pypy to run slower. However, I tried the sane code by @Wolph in that post, that is, running `fib` function many times, and in my computer, pypy runs still slower, with the median time of 10.002002 sec as opposed to the median time of 3.915999 sec by python when `n=500000`. @Wolph's result shows pypy runs faster averagely. So maybe it's related to the large numbers internally, isn't it? – Z-Y.L Jul 28 '21 at 12:00
  • @Z-Y.L This is expected, please read the second answer of the post. Since the numbers get huge, PyPy will not be faster. It can be actually slower in this case for many complex reasons starting from the JIT overhead. Huge numbers cannot be natively computed by your processor so does PyPy. – Jérôme Richard Jul 28 '21 at 23:00

0 Answers0