如何知道一个函数的执行时间简单案例

import datetime, time
def logger(fn):
    def warp(*args, **kwargs):
        # befor 功能增强
        print('args={}, kwargs={}'.format(args, kwargs))
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        # after 功能增强
        duration = datetime.datetime.now() - start
        print("function {} took {}s.".format(fn.__name__, duration.total_seconds()))
        return ret
    return warp

@ logger
def add(x, y):
    print("=== call add ===")
    time.sleep(2)
    return x + x

print(add(4, y=7))
posted @ 2019-01-15 15:24  司家勇  阅读(294)  评论(0编辑  收藏  举报