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

早过忘川 提交于 2019-12-03 18:01:38

问题


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?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/16773362/why-is-the-running-of-pyc-files-not-faster-compared-to-py-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!