lintcode-2089 · 使用 decorator 实现一个函数计时器
描述
decorator 是 Python 中的一类特殊的语法,可以通过 @decorator_name 的方式写在被 decorate 的函数的上面一行。比如这样:
@decorator_name def func(): # do something pass复制代码
decorator 的作用是能够在函数执行之前和之后进行一些处理,而这类处理通常具备一定的通用性,需要包装到多个函数。因此使用 decorator 能够有效的避免重复代码和提升代码可读性。
这个题目的任务是需要你实现一个计时器的 decorator。这个 decorator 的名称被命名为 timer。我们将 timer 包裹在任何函数的外面,那么当这个函数被调用的时候,就会自动记录这个函数的执行时间并打印出来。比如这样:
@timer def func(): pass复制代码
你的任务是编辑 decorators.py
这个文件,实现一个 timer 的 decorator,并打印出函数的名字和被耗费时间。
**
decorator 内部的函数一定要记得 return 哦!
样例
这个题无需任何的输入数据,你可以查看 main.py
这个文件,你的代码在执行了 python main.py
之后应该输出
function func_a cost 0.1 seconds function func_b cost 0.2 seconds复制代码
挑战
必须要用 decorator 的形式来实现,不可以使用其他绕过测试的方法
题解
装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者类)
time.time() 可以获取当前的时间。
format可以格式化数据结果。
import time # write your code here # you need to implement a decorator named timer # the decorator will timer the decorated function and print the name of the # function and the running time in format 'function a cost 0.1 seconds' def timer(func): def warpper(*args,**kwargs): startTime=time.time() func(*args,**kwargs) endTime = time.time() costTime=round(endTime-startTime,1) print("function {func} cost {endTime} seconds".format(func=func.__name__,endTime=costTime)) return warpper @timer def func(): pass
作者:樱舞
链接:https://juejin.cn/post/7019665864479752206