Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PyPy to run a Python program?

Tags:

python

pypy

I have been told that you can use PyPy to run Python programs, which is a lot faster as it is compiled using a JIT compiler rather than interpreted.

The following program finds the largest prime factor of the number 600851475143:

import numpy as np

nr = 600851475143
n = 2

while n <= np.sqrt(nr):
    if nr%n == 0:
        nr = nr/n
    n += 1
print(nr)

What would be the procedure to run this using PyPy?

I know there is documentation on their site, but I do not understand it and would appreciate a demonstration.

like image 962
Jonny Avatar asked Sep 20 '14 10:09

Jonny


People also ask

Can I run Python code in PyPy?

PyPy is a just-in-time compiler that often runs faster than CPython. Most Python code runs efficiently on PyPy except for: Code that depends on Python 3.7+ syntax. Code that depends on CPython extensions, which either does not work or performs poorly when run in PyPy.

Is PyPy faster than Python?

The results: Python needs, on average, 6.7 seconds to execute the code. PyPy needs 9.4 seconds for execution on average. Python is faster.

Can PyPy run Numpy?

TL;DR version: you should use numpy. You can install it by doing pypy -m pip install numpy . You might also be interested in using the experimental PyPy binary wheels to save compilation time. The upstream numpy is written in C, and runs under the cpyext compatibility layer.

Is PyPy as fast as 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

Add this shebang line to the top of the program:

#!/usr/bin/env pypy

If you want to do this manually, just enter pypy main.py on the command-line.

like image 180
simonzack Avatar answered Oct 11 '22 17:10

simonzack