Python inspect.stack很慢 [英] Python inspect.stack is slow

查看:161
本文介绍了Python inspect.stack很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在分析我的Python程序,以查看为什么它看起来很慢.我发现它的大部分运行时间都用在inspect.stack()方法中(用于输出带有模块和行号的调试消息),每次调用的时间为0.005秒.这似乎相当高. inspect.stack真的这么慢吗,还是我的程序出了点问题?

I was just profiling my Python program to see why it seemed to be rather slow. I discovered that the majority of its running time was spent in the inspect.stack() method (for outputting debug messages with modules and line numbers), at 0.005 seconds per call. This seems rather high; is inspect.stack really this slow, or could something be wrong with my program?

推荐答案

inspect.stack()做两件事:

  • 通过从调用方(sys._getframe(1))向解释器询问堆栈帧来收集堆栈,然后遵循所有.f_back引用.这很便宜.

  • collect the stack by asking the interpreter for the stack frame from the caller (sys._getframe(1)) then following all the .f_back references. This is cheap.

,收集文件名,行号和源文件上下文(如果需要,源文件行以及其周围的一些额外行).后者需要读取每个堆栈帧的源文件. 这是昂贵的步骤.

per frame, collect the filename, linenumber, and source file context (the source file line plus some extra lines around it if requested). The latter requires reading the source file for each stack frame. This is the expensive step.

要关闭文件上下文加载,请将context参数设置为0:

To switch off the file context loading, set the context parameter to 0:

inspect.stack(0)

即使 上下文设置为0,由于确定并验证了每个帧的文件名,您仍然会导致每帧文件系统的某些访问.

Even with context set to 0, you still incur some filesystem access per frame as the filename is determined and verified to exist for each frame.

这篇关于Python inspect.stack很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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