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

查看:28
本文介绍了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:

  • 去除所有断言语句.这将防御损坏的程序状态以换取速度.但是,您不需要大量的断言语句才能有所作为吗?您是否有任何代码值得(并且理智?)

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

至于去除文档字符串,它看起来确实像是一个更简单的时代的古怪保留,尽管我猜在内存受限的环境中它可能会有所作为.

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的基本优化模式有什么用?(蟒蛇-O)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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