问题
Given that executing Python bytecode will be faster than running the original source code because Python does not have to recompile, why does Python only save the compiled bytecode when a script is imported? Wouldn't it be better to save the .pyc file for every script that's executed?
回答1:
The startup time of your Python interpreter takes time anyway (even if you might not notice it that much), so it simply doesn't matter and it is more convenient to start a script that might have been updated by you, than always compiling and executing the script manually.
be faster than running the original source code
Btw, Python does not 'run' the source. The initial source from the main script is compiled and executed as well.
Also keep in mind (Introduction to Python):
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.
Further they say:
When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
回答2:
You can always test it. Here's an anectode from my machine:
~$ time python test.py
real 0m0.029s
user 0m0.025s
sys 0m0.004s
~$ time python test.pyc
real 0m0.031s
user 0m0.025s
sys 0m0.004s
来源:https://stackoverflow.com/questions/32447695/why-does-python-only-save-the-bytecode-for-a-script-if-it-is-imported