OrangeTux
OrangeTux

Reputation: 11471

Why is the 'running' of .pyc files not faster compared to .py files?

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

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

Upvotes: 19

Views: 10803

Answers (3)

forsen
forsen

Reputation: 3

The running time of the program is when everything is compiled and the program is executed. Having files already compiled does not speed up execution time, it only speeds up the time TO GET to execution, (compiling all the files into bytecode).

Thus in your second point it would be incorrect to factor compilation time in execution time. When we measure the execution time of programs from varying different languages, all the files are already compiled and ready to go.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363697

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)

Upvotes: 27

Alfe
Alfe

Reputation: 59506

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.

Upvotes: 13

Related Questions