Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidelines to write fast code for PyPy's JIT

PyPy's JIT can make Python code execute much faster than CPython. Are there a set of guidelines for writing code that can be optimised better by the JIT compiler? For example, Cython can compile some static code into C++, and it has guidelines to write efficient code. Are there a set of good practices for PyPy? I know that the PyPy project has guidelines for including hints while writing your own JIT-enabled interpreters for other dynamic languages, but that is not relevant to most end users of the framework, who are simply using the interpreter. Questions I am wondering about include:

  1. Packaging a script into functions
  2. Explicitly deleting variables
  3. Possible ways of giving, or hinting variable types
  4. Writing loops a certain way
like image 372
highBandWidth Avatar asked Mar 15 '11 21:03

highBandWidth


People also ask

How JIT compilers are implemented and fast?

JITs can inline by changing the code at runtime to make it faster(compiled languages just inline statically).

How much faster is PyPy?

On the average, PyPy speeds up Python by about 7.6 times, with some tasks accelerated 50 times or more. The CPython interpreter simply doesn't perform the same kinds of optimizations as PyPy, and probably never will, since that is not one of its design goals.

How do I use PyPy instead of Python?

For Python 2.7, it's just called pypy . For CPython, if you would like to run Python 3 from the terminal, you simply enter the command python3 . To run PyPy, simply issue the command pypy3 . Entering the pypy3 command in the terminal might return the Command 'pypy3' not found message, as shown in the next figure.

Is PyPy faster than C++?

Pypy is as fast as or faster than c/c++ in some applications/benchmarks. And with python (or interpreted langs in general) you gain a repl, a shorter write -> compile -> test loop, and generally speaking a higher rate of development.


1 Answers

PyPy wiki's at BitBucket has a section on JIT Friendliness. Some blog posts offer further advice on making code run fast in PyPy, but AFAIK the idea is that idiomatic code that doesn't force interpreting/realizing frames should be fast and is a bug if it isn't.

I know that for 3, some "assert x > 0" or similar statements can be useful, but I don't remember where I saw that. I also believe I've seen some suggestion about refactoring conditional-paths-in-loops related to 4 (edit: this seems to be outdated now).

Here's a thread with some related discussion. You can check how well the JIT is working with your code with jitviewer, but it's somewhat advanced. Joining #pypy on Freenode will get you help with jitviewer and your particular code.

like image 76
TryPyPy Avatar answered Sep 18 '22 13:09

TryPyPy