16
votes

I know the difference between a .py and a .pyc file. My question is not about how, but about why According to the docs:

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.

.pyc files load imports faster. But after loading the 'running' part of .pyc files takes the same time as the 'running' part in .py files? Why is is this? I would expected that

  • bit code (.pyc) is closer to the Python Virtual Machine and thus runs faster
  • .py files are being compiled to .pyc before they are being executed. This takes an extra step and thus costs time.

My question: After the import part, Why does the running part of .pyc files doesn't speed up execution compared to .py files?

2

2 Answers

23
votes

When you run a .py file, it is first compiled to bytecode, then executed. The loading of such a file is slower because for a .pyc, the compilation step has already been performed, but after loading, the same bytecode interpretation is done.

In pseudocode, the Python interpreter executes the following algorithm:

code = load(path)
if path.endswith(".py"):
    code = compile(code)
run(code)
11
votes

The way the programs are run is always the same. The compiled code is interpreted.

The way the programs are loaded differs. If there is a current pyc file, this is taken as the compiled version, so no compile step has to be taken before running the command. Otherwise the py file is read, the compiler has to compile it (which takes a little time) but then the compiled version in memory is interpreted just like in the other way.