我的Python 3项目大量使用cython。
在生产部署中,我使用了一个构建脚本,该脚本除其他外禁用了性能分析:
from distutils.core import setup
from Cython.Build import cythonize
import os
compiler_directives = {
'language_level': 3,
'optimize.use_switch': True,
'profile': True,
}
setup(
packages=["XXXXXX"],
ext_modules=cythonize(
module_list="**/*.pyx",
compiler_directives=compiler_directives,
)
)
在开发中,我正在使用pyximport。为了使这两种上下文有所不同,我正在测试项目的顶级
__init__.py
文件中是否使用了“生产”用户。如果这不是生产性产品,那么我将使用pyximport; pyximport.install
,以使其变得完全透明:if getpass.getuser != PRODUCTION_USER_NAME:
import pyximport
pyximport.install(
pyximport=True,
pyimport=False,
build_dir=None,
build_in_temp=True,
setup_args={},
reload_support=False,
load_py_module_on_import_failure=False,
inplace=False,
language_level=3,
)
我想在开发环境中为所有cython文件启用分析。我试图将
profile=True
参数添加到piximport.install
语句中,但是它不起作用。我该如何进行?
一些其他评论:
Profile=True
并在提交之前将其删除... .pyxbld
文件不是一个选择,因为我有46个pyx文件,并计划有更多...除非像我对构建脚本所做的那样,只有一种方法可以设置一个文件来支持所有pyx,但是我没有没找到如何。 谢谢你的帮助。
最佳答案
它需要包装pyximport的内部函数之一,但是可以做到这一点:
# Allow .pyx files to be seamlessly integrated via cython/pyximport with
# default compiler directives.
import functools
import pyximport.pyximport
# Hack pyximport to have default options for profiling and embedding signatures
# in docstrings.
# Anytime pyximport needs to build a file, it ends up calling
# pyximport.pyximport.get_distutils_extension. This function returns an object
# which has a cython_directives attribute that may be set to a dictionary of
# compiler directives for cython.
_old_get_distutils_extension = pyximport.pyximport.get_distutils_extension
@functools.wraps(_old_get_distutils_extension)
def _get_distutils_extension_new(*args, **kwargs):
extension_mod, setup_args = _old_get_distutils_extension(*args, **kwargs)
if not hasattr(extension_mod, 'cython_directives'):
extension_mod.cython_directives = {}
extension_mod.cython_directives.setdefault('embedsignature', True)
extension_mod.cython_directives.setdefault('profile', True)
return extension_mod, setup_args
pyximport.pyximport.get_distutils_extension = _get_distutils_extension_new
pyximport.install()
请注意,这不会强制使用新选项重新编译未更改的模块。您将必须
touch
这些文件以使用新配置触发编译。关于python - Cython:pyximport:在pyximport.install中启用性能分析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30028253/