测量时间的 Python 上下文管理器

标签 python with-statement

我正在努力制作一段代码,允许测量在“with”语句中花费的时间并将测量的时间( float )分配给“with”语句中提供的变量。

import time

class catchtime:
    def __enter__(self):
        self.t = time.clock()
        return 1

    def __exit__(self, type, value, traceback):
        return time.clock() - self.t

with catchtime() as t:
    pass

此代码留下 t=1 而不是 clock() 调用之间的区别。如何解决这个问题?我需要一种从退出方法中分配新值的方法。

PEP 343 describes更详细地介绍了 contect manager 是如何工作的,但我不明白其中的大部分内容。

最佳答案

这是一个使用 contextmanager 的例子

from time import perf_counter
from contextlib import contextmanager

@contextmanager
def catchtime() -> float:
    start = perf_counter()
    yield lambda: perf_counter() - start


with catchtime() as t:
    import time
    time.sleep(1)

print(f"Execution time: {t():.4f} secs")

输出:

执行时间:1.0014 秒

关于测量时间的 Python 上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987060/

相关文章:

python - 具有 __index__() 方法的 Python 对象示例?

python - 为 python 安装设置工具

python - 使用 matplotlib 从纪元开始绘制 time() 的日期

python - 遍历多个数据框

python - Python : generator didn't yield error 中的自定义 'with open()' 语句

sql - 使用 with 语句创建 View

java - 是否有与 Javascript 的 with 语句等效的 Java?

python - with语句,自动删除对象

python - tf.constant 与 tf.placeholder

Python 多行 with 语句