使用装饰器记录执行时间

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

@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上的一篇很好的文章.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...