Python优化(-O或PYTHONOPTIMIZE)有什么作用? [英] What does Python optimization (-O or PYTHONOPTIMIZE) do?

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

问题描述

文档只说Python解释器执行基本优化",而没有涉及任何细节.显然,它取决于实现方式,但是有什么方法可以使人们知道可以优化哪种类型的东西,以及可以节省多少运行时间?

The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it could generate?

使用-O是否有不利之处?

Is there any downside to using -O?

我唯一知道的是-O禁用了assert,但是对于在生产中仍然可能出错的事情,大概不应该使用assert.

The only thing I know is that -O disables assert, but presumably one shouldn't use assert for things that could still go wrong in production.

推荐答案

在Python 2.7中,-O具有以下作用:

In Python 2.7, -O has the following effect:

  • the byte code extension changes to .pyo
  • sys.flags.optimize gets set to 1
  • __debug__ is False
  • asserts don't get executed

此外,-OO具有以下作用:

要验证不同版本的CPython的效果,请grep Py_OptimizeFlag的源代码.

To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag.

链接到官方文档: https://docs.python .org/2.7/tutorial/modules.html#compiled-python-files

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

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