简体   繁体   English

具有可变格式的装饰器计时器功能(小数位)?

[英]Decorator timer function with variable formatting (decimal places)?

I am trying to create a decorator for a timer so that i can easily call @decoratortimer for my functions to time the amount of time taken my function took to run. 我正在尝试为计时器创建一个装饰器,以便可以轻松地为函数调用@decoratortimer来计时函数运行所花费的时间。

However, I cant seem to be able to make my decorator function variable such that I can change the number of decimal places as per user request. 但是,我似乎无法将我的装饰器函数设置为变量,以便我可以根据用户请求更改小数位数。

import time

def decoratortimer(decimal):
    def decoratorfunction(f):
        def wrap(*args, **kwargs):
            time1 = time.time()
            result = f(*args, **kwargs)
            time2 = time.time()
            print('{:s} function took {:{}f} ms'.format(f.__name__, ((time2-time1)*1000.0), decimal ))
            return result
        return wrap
    return decoratorfunction

@decoratortimer(2)
def callablefunction(name):
    print(name)
print(callablefunction('John'))

#outputs "callablefunction function took 1.008511 ms"

As you can see from my code, I've formatted my string as such, 如您从我的代码中看到的那样,我已经格式化了我的字符串,

print('{:s} function took {:{}f} ms'.format(f.__name__, ((time2-time1)*1000.0), decimal ))

My expected output is that it is supposed to print out callablefunction function took 1.01 ms because i've passed in the integer value of 2 for my decimal places in @decoratortimer . 我的预期输出是应该打印出callablefunction function took 1.01 ms因为我已经将@decoratortimer小数位传递给整数2。

Could I be formatting my string wrongly? 我会错误地格式化我的字符串吗? I have looked at this and tried to emulate it but still cant get my decorator function to work! 我已经看过这个并尝试模仿它,但仍然无法使我的装饰器功能正常工作! Please help, I cant seem to wrap my head around this. 请帮助,我似乎无法解决这个问题。 (No pun intended). (无双关语)。

Replace {:{}f} with {:.{}f} to get the number of decimal places. {:{}f}替换为{:.{}f}以得到小数位数。

Another topic: consider using time.monotonic instead of time.time for this case. 另一个主题:在这种情况下,请考虑使用time.monotonic代替time.time If the system clock gets an update during your function runs, the result may become negative. 如果在函数运行期间系统时钟得到更新,则结果可能为负。 time.monotonic is guaranteed to increase. time.monotonic保证增加。 The values themselves are not relevant, only the difference between them is. 这些值本身并不相关,只有它们之间的差异才有意义。 ( docs ) docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM