Discuss / Python / 作业,两种思路一种示例版一种偷懒版。

作业,两种思路一种示例版一种偷懒版。

Topic source

import functools,time 示例版: def metric(fn): @functools.wraps(fn) def wrapper(): start = time.time() fn() end = time.time() print('%s executed in %.2f ms' % (fn.name,end-start)) return wrapper

@metric def aaa(): time.sleep(1) print('Hello World!')

aaa()

偷懒版: def metric(fn): start = time.time() fn() end = time.time() print('%s executed in %.2f ms' % (fn.name,end-start))

def aaa(): time.sleep(1) print('Hello World!')

metric(aaa)

用到了time模块,可以获取函数运行前和运行后的时间,然后再一减就是函数运行时间,这里我用了time.sleep(1)延迟1秒来验证正确性,不然运行速度太快看不出结果。


  • 1

Reply