How much faster does PyPy make your existing Python code?
Python is an interpreted language, which mostly runs in a runtime known as CPython. While not too bad for most tasks, CPython can be a bit slow for larger programs. So, PyPy allows you to run your existing Python code, without any changes, at a much faster speed. This is in part due to the JIT(Just in Time) compiler, which is faster after it has a bit of time to warm up. PyPy may even decrease the memory usage of memory hungry programs, although this isn’t guaranteed.
You can learn more about PyPy by visiting their website.
Installation On Ubuntu
Since Ubuntu is amazing, all it takes is one command to install:
sudo apt install pypy
After the command is done, you can run most Python programs by running:
Here’s a very non-scientific benchmark that probably has unrealistic results. Each program will be run 5 times, and the fastest run will be displayed.
My favorite benchmarks for programming languages is how long it takes to find all prime numbers up to a certain number. In Python, the fastest implementation I have so far is the following program.
import math, sys
def is_prime( num ):
if num <= 1:
if num == 2:
for i in range(2, int( math.sqrt( num ) + 1 ) ):
if num % i == 0:
for x in range( 0, int( sys.argv ) + 1 ):
if is_prime( x ):
print( x )
Since I believe both PyPy and CPython cache the bytecode to some extent, I’ll run both a few times so they get a chance to cache what they need.
In order to show the difference for programs with a short runtime, I’ll first benchmark the programs by just finding all prime numbers up to 1000. It’s probably also worth mentioning that I’m redirecting all the output to
/dev/null to not waste time printing.
As you can see, with short running programs, PyPy actually makes everything slower. Let’s bump it up to all prime numbers from 0 to 100,000 and see what happens.
This actually took longer than I expected. I thought it would be near-instant, but apparently not.
This is actually noticeably faster than CPython, despite not making any changes to the code.
The final test, finding all prime numbers from 0 to one million.
This actually took a rather long time. Well, I hope PyPy fares better.
Wow, that’s actually a big difference of nearly 8x. It’s not just me either, the PyPy website also says that PyPy is faster by a factor of 7.6:
It depends greatly on the type of task being performed. The geometric average of all benchmarks is 0.13 or 7.6 times faster than CPython. — PyPy
Use PyPy For Programs That Take A While
For most small programs, it doesn’t really make that much of a difference. In fact, small programs will often take longer to run with PyPy. But, if you need a program to run faster, and don’t want to change languages, PyPy definitely makes a big difference.
You can even use PyPy for Fail2Ban: