Python基本优化模式的用途是什么? (python -O) [英] What is the use of Python's basic optimizations mode? (python -O)

查看:119
本文介绍了Python基本优化模式的用途是什么? (python -O)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python有一个标志-O,可用于执行解释器.该选项将生成优化的"字节码(写入.pyo文件),并给出两次,它将丢弃文档字符串.在Python的手册页中:

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 will discard docstrings. From Python's man page:

-O打开基本优化.这将更改文件扩展名 用于从.pyc到.pyo的已编译(字节码)文件.给两次 导致文档字符串被丢弃.

-O Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. Given twice, causes docstrings to be discarded.

该选项的两个主要功能是:

This option's two major features as I see it are:

  • 剥离所有断言语句.这以防御损坏的程序状态为代价来换取防御.但是,您是否不需要大量的assert语句来对此有所作为?您是否有任何值得这样做的代码(理智?)

  • Strip all assert statements. This trades defense against corrupt program state for speed. But don't you need a ton of assert statements for this to make a difference? Do you have any code where this is worthwhile (and sane?)

剥离所有文档字符串.在哪个应用程序中,内存使用如此重要,这才是制胜法宝?为什么不将所有内容推送到用C编写的模块中?

Strip all docstrings. In what application is the memory usage so critical, that this is a win? Why not push everything into modules written in C?

此选项的用途是什么? 它具有现实价值吗?

What is the use of this option? Does it have a real-world value?

推荐答案

在剥离assert语句时:这是C语言世界中的标准选项,许多人认为ASSERT定义的一部分在于它不能在生产代码.剥离它们是否有所不同,取决于有多少个断言而不是取决于这些断言完成多少工作:

On stripping assert statements: this is a standard option in the C world, where many people believe part of the definition of ASSERT is that it doesn't run in production code. Whether stripping them out or not makes a difference depends less on how many asserts there are than on how much work those asserts do:

def foo(x):
    assert x in huge_global_computation_to_check_all_possible_x_values()
    # ok, go ahead and use x...

当然,大多数断言都不是那样,但是重要的是要记住,您可以做类似的事情.

Most asserts are not like that, of course, but it's important to remember that you can do stuff like that.

对于剥离docstrings,从更简单的时间来看,它看起来像是一个古朴的保留,尽管我猜在内存受限的环境中,它可能会有所作为.

As for stripping docstrings, it does seem like a quaint holdover from a simpler time, though I guess there are memory-constrained environments where it could make a difference.

这篇关于Python基本优化模式的用途是什么? (python -O)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆