Speed up your Python code with PyPy
Python is one of the most popular programming languages nowadays. Due to its simplicity, developers can focus on solving the problem itself and they don’t need to spend too much time in understanding the syntax or behavior of the programming language. There are so many applications for Python but it’s mostly used by data scientists and web developers. However, Python is much slower than C or C++ which is quite a huge drawback. Maybe you’re wondering how to speed up your Python code little bit. Well, this is the time when PyPy comes into the play. PyPy is a fast, compliant interpreter of Python. Its just-in-time compiler brings a significant speed improvement over CPython, which is a standard Python interpreter. Most of the Python code runs well on PyPy but there are several libraries written in C that cannot be used with it so it doesn’t have full compatibility with the Python ecosystem which you need to consider. Anyway it’s offering a significant speed improvement and it could be very handy in many cases.
Here’s an example of executing a simple script with both Python and PyPy. You can see the execution time comparison here:
What’s happening is that PyPy starts like an interpreter running our Python code directly from the source file. However, instead of running the code line by line, it compiles parts of the code to machine code just before it executes them: „Just in time“. In that manner, compilation is a combination between interpretation and ahead-of-time compilation and that’s the reason why we achieved a better performance with PyPy.
Every week you will be able to get through some hacks, tips and best practices related to the process automation. See you next time!
Article by Štefan Mastiľák, Anton Hajdu & Dominik Mesaroš