Why Compile Python Code

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a
compiled script has a faster startup
time (as it doesn't need to be
compiled), it doesn't run any
faster.

What's preventing python from being compiled?

Python, the language, like any programming language, is not in itself compiled or interpreted. The standard Python implementation, called CPython, compiles Python source to bytecode automatically and executes that via a virtual machine, which is not what is usually meant by "interpreted".

There are implementations of Python which compile to native code. For example, the PyPy project uses JIT compilation to get the benefits of CPython's ease of use combined with native code performance.

Cython is another hybrid approach, generating and compiling C code on the fly from a dialect of Python.

However, because Python is dynamically typed, it's not generally practical to completely precompile all possible code paths, and it won't ever be as fast as mainstream statically typed languages, even if JIT-compiled.

Any speed benefit to compiling Python code?

No. py2exe and similar tools just create a bundle including the Python interpreter, the bytecode of your Python sources and their dependencies. It's just a deploy convenience, there's no speed advantage (besides skipping the initial parsing of the .py files; in this respect, it's like running your code the second time when the .pyc files are already created).

For "out of the box" performance improvement you can try running your script with PyPy instead of CPython - for "all interpreted" (=> no numpy & co.) numerical Python code I saw very often 20x speedups.

Compiling Python

python yourfile.py

You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.

http://www.python.org/download/

How to compile python script importing modules to executable using cython

you can use this answer:
Building Cython-compiled python code with PyInstaller

to bundle everything together (use cython and then pack everything using pyinstaller which should pack all the packages)



Related Topics



Leave a reply



Submit