Discuss / Python / 第二题:请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间。

第二题:请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间。

Topic source

#其实多嵌套一层,做一个IF判断就行了。这题感觉昨晚对“返回函数”和“装饰器”,理解会更深刻。 def log(argLog,**kw): def Logout(fn): @functools.wraps(fn) def metric(args, kw): if callable(argLog[0]): print("begin call Func: %s" % (fn.name)) else: print("begin call Func: [%s] %s" % (argLog[0], fn.name)) result = fn(*args, kw) if callable(argLog[0]): print("end call Func: %s" % (fn.name)) else: print("end call Func: [%s] %s" % (argLog[0], fn.name)) return result return metric if callable(argLog[0]): return Logout(argLog[0]) else: return Logout

@log
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@log('excute')
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

if __name__ == "__main__":
    # 测试Test Case
    f = fast(11,22)
    s = slow(11, 22, 33)
    if f != 33:
        print('测试失败!')
    elif s != 7986:
        print('测试失败!')
    else:
        print("Test is pass!")

  • 1

Reply