Today, we will introduce the process control for Python compilation. The following article describes how to optimize the bytecode and the code to be optimized through Python, the following article describes the process control steps of Python compilation.
This section describes how to "slightly" Process Control of Python compilation. This is just a little bit because Python will perform some simple Optimization (basic Peephole Optimization) on bytecode in any case. For more information, see the Python source code. Python 2.5 is located in Python/compile. c, and Python 2.7 is located in Python/peephole. c ). These optimizations cannot be disabled through environment variables or command parameters. For example:
- if True:
- return 1
- else:
- return 0
Will be optimized:
- return 1
More optimizations are being added to the Python source code. Only three parameters can affect Python compilation optimization:
First, remove all assert statements and set the value of the built-in Variable _ debug _ to False. The method is to add parameters in the command line when running Python:
- python -O im.py
2. Remove all docstrings in addition to the first one. The method is to add parameters in the command line when running Python:
- python -OO im.py
Third, by default, for a module, the Python compiled bytecode will be saved to the same folder as the source code. In this way, the loading speed of the module can be accelerated. Most friends who use Python have written programs that contain two or three files. In addition to the. py file, the. pyc file is also found in the folder.
The mymodule. pyc file is the bytecode of mymodule. py. If the command line running Python contains the "-O" or "-OO" parameter, Python saves the optimized bytecode to the mymodule. pyo file. To disable the generation of. pyc or. pyo files, you can add parameters in the command line when running Python:
- python -B im.py
You can also set environment variables:
- c:\> set PYTHONDONTWRITEBYTECODE=x
After reading the above three instructions, some friends may doubt that the "-O" and "-OO" parameters really do the three things? Unfortunately, this is true. At least in Python2.5. Therefore, adding the "-O" parameter does not significantly optimize the running speed of Python. The true functions of these two options are to differentiate the debugging version and the release version. Add as many assert statements as possible in the program so that the programmer can discover some hidden errors during the debugging stage. These statements are removed during release. If your software is commercial software, adding the "-OO" parameter can make it difficult for others to see the purpose of internal functions and increase the difficulty of cracking. With this, who said that Python cannot write commercial software? The above article is a detailed introduction to the actual application solution of Python compilation process control.