用装饰器记录执行时间 [英] Logging execution time with decorators
问题描述
尝试了一段时间失败后,我正在这个神奇的网站上寻求帮助.现在解决我的问题:我想创建一个装饰器,将一个函数的执行时间( 在该函数执行期间)写到以下日志文件中:>
After I tried unsuccessfully for a while, I am seeking help from this miraculous website. Now for my problem: I want to create a decorator that writes the elapsed execution time of a function (during the execution of the function) into a logging file like:
@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
有什么想法吗?
推荐答案
好吧,我最终发现了一些线程问题.感谢您的所有建议!
Okay, I figured something out in the end with threads. Thanks for all the suggestions!
import codecs, threading, time
from functools import wraps
def log_time(logpath="log.txt", interval=5):
def log_time_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
t = threading.Thread(target=func, args=args, kwargs=kwargs)
log_entries = 0
with codecs.open(logpath, "wb", "utf-8") as logfile:
start_time = time.time()
t.start()
while t.is_alive():
elapsed_time = (time.time() - start_time)
if elapsed_time > interval * log_entries:
m, s = divmod(elapsed_time, 60)
h, m = divmod(m, 60)
logfile.write("Elapsed time: %2dh %2dm %2ds\n" %(h, m, s))
log_entries += 1
return wrapper
return log_time_decorator
一个缺点可能是您无法轻松检索该函数的返回值(至少我还没有弄清楚它).
One disadvantage might be that you cannot easily retrieve the return value of the function (at least I haven't figured it out yet).
删除了不必要的变量并添加了一种不错的日志记录格式(请参见此)
Removed an unnecessary variable and added a nice format for logwriting (see this)
即使其他用户拒绝了他的编辑,我也想加入 Piotr Dabkowski ,因为它可以使用返回值:
Even though other users rejected his edit, I want to include a version from Piotr Dabkowski because it works with a return-value:
def log_time(logpath="log.txt", interval=5):
def log_time_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
RESULT = [None]
def temp():
RESULT[0] = func(*args, **kwargs)
t = threading.Thread(target=temp)
log_entries = 0
with codecs.open(logpath, "wb", "utf-8") as logfile:
start_time = time.time()
t.start()
while t.is_alive():
elapsed_time = (time.time() - start_time)
if elapsed_time > interval * log_entries:
m, s = divmod(elapsed_time, 60)
h, m = divmod(m, 60)
logfile.write("Elapsed time: %2dh %2dm %2ds\n" %(h, m, s))
log_entries += 1
return RESULT[0]
return wrapper
return log_time_decorator
这篇关于用装饰器记录执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!