Why compile Python code?

后端 未结 10 1788
时光取名叫无心
时光取名叫无心 2020-11-27 09:37

Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?

I also notic

相关标签:
10条回答
  • 2020-11-27 09:54

    Beginners assume Python is compiled because of .pyc files. The .pyc file is the compiled bytecode, which is then interpreted. So if you've run your Python code before and have the .pyc file handy, it will run faster the second time, as it doesn't have to re-compile the bytecode

    compiler: A compiler is a piece of code that translates the high level language into machine language

    Interpreters: Interpreters also convert the high level language into machine readable binary equivalents. Each time when an interpreter gets a high level language code to be executed, it converts the code into an intermediate code before converting it into the machine code. Each part of the code is interpreted and then execute separately in a sequence and an error is found in a part of the code it will stop the interpretation of the code without translating the next set of the codes.

    Sources: http://www.toptal.com/python/why-are-there-so-many-pythons http://www.engineersgarage.com/contribution/difference-between-compiler-and-interpreter

    0 讨论(0)
  • 2020-11-27 09:57

    Something not touched upon is source-to-source-compiling. For example, nuitka translates Python code to C/C++, and compiles it to binary code which directly runs on the CPU, instead of Python bytecode which runs on the slower virtual machine.

    This can lead to significant speedups, or it would let you work with Python while your environment depends on C/C++ code.

    0 讨论(0)
  • 2020-11-27 10:05

    It's compiled to bytecode which can be used much, much, much faster.

    The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

    Important addition by Ben Blank:

    It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

    0 讨论(0)
  • 2020-11-27 10:05

    As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.

    Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.

    You can read more about this in the Python documentation.

    0 讨论(0)
提交回复
热议问题