【问题标题】:Decorator-like syntax for a specific line of code特定代码行的类似装饰器的语法
【发布时间】:2018-12-07 05:17:37
【问题描述】:

链接主题(但不重复):Decorator to time specific lines of the code instead of whole method?

我知道装饰器通常如何用于 Python 函数。

单行代码是否有类似的概念/语法?

例子:用

def measuretime(lineofcode):
    start = time.time()
    lineofcode()
    print time.time() - start

然后

@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))

会被解释为

start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start

注意事项:

  • 我知道像这样测量执行时间并不是最佳选择,最好使用timeit 等,但这只是一个随机示例来展示我正在寻找的内容(单行代码的装饰器)

  • 我正在寻找 1 或 2 行代码解决方案(当然是函数的定义)。如果解决方案需要超过 2 行代码(即比 @measuretime 之类的代码更多),那么最好放弃并正常执行:

      start = time.time()
      im = Image.open(BytesIO(base64.b64decode(data)))
      print time.time() - start
    

【问题讨论】:

  • 为了测试?使用jupyter%timeit
  • @Sraw 我已经在问题中提到了timeit,而且我没有使用jupyter/ipython,而是在脚本模式下使用Python,即python script.py

标签: python decorator python-decorators


【解决方案1】:

不,但最接近您的目标的方法是使用上下文管理器来覆盖一行代码。

import time

class timer(object):
    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, *args):
        self.end = time.clock()
        self.interval = self.end - self.start
        print(self.interval)

with timer():
    [i for i in range(100000)]

这会在我的电脑上输出以下内容:

0.005583688506699192

【讨论】:

    【解决方案2】:

    语言中没有这样的东西,尽管您可以尝试查看jupyter(以前称为ipython)。它有%%timeit 快捷方式。

    【讨论】:

      【解决方案3】:

      如果你想在一行代码之前和之后做一些事情,context manager 是合适的:

      from contextlib import contextmanager
      import time
      
      @contextmanager
      def measuretime():
          start = time.time()
          try:
              yield
          finally:
              print(time.time() - start)
      
      with measuretime():
          do_stuff()
      

      【讨论】:

      • 不错的解决方案,看来我正在寻找!
      【解决方案4】:

      没有。装饰器基本上是一个将另一个函数作为参数并返回“装饰”函数的函数。 @decorator 只是一个语法糖。

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 2018-10-25
        • 2012-01-28
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 2014-01-14
        相关资源
        最近更新 更多