使用装饰器记录执行时间

在我尝试了一段时间失败之后,我正在寻求这个神奇网站的帮助.现在我的问题是:我想创建一个装饰器,将函数的执行时间(在执行函数期间)写入日志文件,如:

@log_time("log.txt", 35)
def some_function(...):
    ...
    return result

from functools import wraps

def log_time(path_to_logfile, interval):
    ...

所以log.txt看起来像

Time elapsed: 0h 0m 35s
Time elapsed: 0h 1m 10s
Time elapsed: 0h 1m 45s

有任何想法吗?

最佳答案 我将为您提供有关为实现此目的必须执行的操作的基本概述.以下是装饰器,它接受两个参数,并执行该函数.缺少的功能表示为注释,将它们添加到:

def log_time(path_to_logfile, interval):
    def log(func):
        # 'wrap' this puppy up if needed 
        def wrapped(*args, **kwargs):
            # start timing
            func(*args, **kwargs)
            # stop timing
            with open(path_to_logfile, 'a') as f:
                pass # functionality
        return wrapped
    return log

您现在可以装饰函数,输出将写入path_to_logfile.所以,例如,在这里装饰foo:

@log_time('foo.txt', 40)
def foo(i, j):
    print(i, j)

foo(1, 2)

将采取foo并执行它.您需要适当地计时并将内容写入您的文件.您应该更多地尝试装饰器并阅读它们,这是Decorators exist at the Python Wiki上的一篇很好的文章.

点赞