What is the use of Python's basic optimizations mode? (python -O)

后端 未结 7 741
终归单人心
终归单人心 2020-12-25 10:24

Python has a flag -O that you can execute the interpreter with. The option will generate \"optimized\" bytecode (written to .pyo files), and given twice, it wil

7条回答
  •  长情又很酷
    2020-12-25 10:27

    If you have assertions in frequently called code (e.g. in an inner loop), stripping them can certainly make a difference. Extreme example:

    $ python    -c 'import timeit;print timeit.repeat("assert True")'
    [0.088717937469482422, 0.088625192642211914, 0.088654994964599609]
    $ python -O -c 'import timeit;print timeit.repeat("assert True")'
    [0.029736995697021484, 0.029587030410766602, 0.029623985290527344]
    

    In real scenarios, savings will usually be much less.

    Stripping the docstrings might reduce the size of your code, and hence your working set.

    In many cases, the performance impact will be negligible, but as always with optimizations, the only way to be sure is to measure.

提交回复
热议问题