timeit 通过关闭垃圾收集有什么好处?
我正在阅读 timeit 模块的代码,我注意到这一段:
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
这只是存储垃圾收集的状态(打开或关闭),然后将其关闭。函数inner
执行正在计时的语句。然后它将垃圾收集器恢复到原来的状态。
所以我很好奇这有什么意义。如果正在测试的代码可以在垃圾收集器中工作,那么这不应该反映在测试中吗?我缺少什么?
I was reading the code for the timeit module and I noticed this segment:
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
This just stores the state of garbage collection (on or off) and then turns it off. The function inner
executes the statement being timed. It then reverts the garbage collector to its old state.
So I'm curious about what the point of this is. If the code being tested works the garbage collector, then shouldn't that be reflected in the testing? What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
垃圾收集的本质是其频率和持续时间在某种程度上是不可预测的。至少从特定代码块的性能的角度来看,垃圾收集器只是给统计数据增加了噪音。
从整个程序的角度来看,如果您的程序运行在使用垃圾收集器的系统上,那么您是正确的,那么在衡量程序性能时应该考虑到这一点。但它通常不会被考虑到单独的功能中。
The nature of garbage collection is that its frequency and duration is somewhat unpredictable. At least from the point of view of the performance of a specific chunk of code, the garbage collector just adds noise to the statistics.
From a whole-program point of view, you are correct in that if your program is running on a system where the garbage collector is exercised, then yes that should be taken into account when measuring the program performance. But it's not usually factored in for individual functions.
代码肯定应该这样写吗?
否则,如果定时代码抛出异常,垃圾收集将保持禁用状态。
我在 bugs.python.org 上报告了这个问题,它已在 Python 2.7.3 和 3.2.2 中修复。
Surely that code should be written like this?
Otherwise garbage collection will remain disabled if the timed code throws an exception.
I reported this on bugs.python.org, and it was fixed in Python 2.7.3 and 3.2.2.