Domanda

We can write a piece of python code and put it in already compiled ".pyc" file and use it. I am wondering that is there any kind of gain in terms of performance or it is just a kind of modular way of grouping the code.

Thanks a lot

È stato utile?

Soluzione

There is no performance gain over the course of your program. It only improves the startup time.

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html

And pyo files being the next optimization just remove doc strings from your code.

Altri suggerimenti

I'm not sure about .pyc files (very minor gain is at least not creating .pyc files again), but there's a '-O' flag for the Python interpreter which produces optimised bytecode (.pyo files).

You will gain the fraction of a second it took the Python runtime to parse and compile the source into bytecode, which only happens on first run/import.

You will lose portability.

See here.

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

Yes, simply because the first time you execute a .py file, it is compiled to a .pyc file. So basically you have to add the compilation time. Afterwards, the .pyc file should be always used.

Based on the accepted answer of this question: Why are main runnable Python scripts not compiled to pyc files like modules?.

When a module is loaded, the py file is "byte compiled" to pyc files. The time stamp is recorded in pyc files. This is done not to make it run faster but to load faster

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top