Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

python - 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

  • 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...