James
James

Reputation: 4050

Am I using PyPy wrong? It's slower 10x than standard Python

I have heard good stuff about PyPy. In particular I'd heard that it was very fast which made me wonder if it might be usable for an embedded project I have.

I downloaded PyPy-2.6 for my Windows 7 PC, and unzipped the contents into a directory.

I've written a small test program to allow me to benchmark:


import time

def fib(n):
        if n == 0 or n == 1:
                return 1
        return fib(n - 1) + fib(n - 2)

t0 = time.time()
fib(20)
t1 = time.time()

print t1-t0

So I went to the directory where PyPy was unzipped, ran ./pypy.exe hello.py and got an answer of 0.120.

Then I fired up a cygwin console and ran python hello.py and got an answer of 0.01.

Am I using PyPy wrong or is it only faster for certain applications?

Edit

Thanks to Rob who pointed out that the JIT compiler needs time to warm up.

Extending my sample code produces the following results:

n     PyPy    Python
20    0.12     0.01
25    0.15     0.06
30    0.34     0.67
35    0.92     7.39
40    10.98    82.9

It seems like there's a 0.1 second start-up cost or something, but after that it's faster.

Upvotes: 3

Views: 1813

Answers (1)

Robᵩ
Robᵩ

Reputation: 168616

It is only faster for certain applications. Quoting the PyPy doc:

There are two cases that you should be aware where PyPy will not be able to speed up your code:

  • Short-running processes: if it doesn't run for at least a few seconds, then the JIT compiler won't have enough time to warm up.

  • If all the time is spent in run-time libraries (i.e. in C functions), and not actually running Python code, the JIT compiler will not help.

Since your program seems to run on the order of 10-2 or 10-1 seconds, the JIT compiler doesn't do you any good.

Upvotes: 5

Related Questions