zoukankan      html  css  js  c++  java
  • 实现多函数计时功能--及装饰器实现

    现在有一个新的需求,希望可以记录下函数的执行时间,于是在代码中添加日志代码:

    import time

    def foo():
        start_time=time.time()
        print('hello foo')
        time.sleep(3)
        end_time=time.time()
        print('spend %s'%(end_time-start_time))
     
    foo()
    bar()、bar2()也有类似的需求计时,怎么做?再在bar函数里调用时间函数?这样就造成大量雷同的代码,为了减少重复写代码,我们可以这样做,重新定义一个函数:专门设定时间show_time:
    import time
    def show_time(func):
        start_time=time.time()
        func()
        end_time=time.time()
        print('spend %s'%(end_time-start_time))
     
     
    def foo():
        print('hello foo')
        time.sleep(3)
     
    show_time(foo)
     
     
    那利用装饰器实现:
    import time
    def show_time(f):
    def inner():
    start_time=time.time()
    f()
    end=time.time()
    print('spend %s' %(end-start_time))
    return inner
    @show_time
    def bar():
    print('hello bar')
    time.sleep(3)
    bar()
    @show_time
    def foo():
    print('hello foo')
    time.sleep(5)
    foo()
    这样就即没有更改原代码,也没修改调用方式了
    那什么是装饰器?
    :装饰器也是一特殊函数,装饰就是添加新的功能--为你之前的函数foo(),bar()添加某个功能--如计时功能,所以show-time函数就叫一装饰器!!
  • 相关阅读:
    第一次软件作业
    第四次作业之单元测试
    第四次作业之代码规范
    第四次作业之psp
    第四次作业之四则运算
    第三周作业之功能测试
    第三周作业之效能分析
    第三周作业之例行报告
    第二周例行报告(王伟东)
    软件工程第二次作业(王伟东)
  • 原文地址:https://www.cnblogs.com/dbslinux/p/11192712.html
Copyright © 2011-2022 走看看