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函数就叫一装饰器!!
  • 相关阅读:
    vue之条件渲染
    webstorm(三):webstorm的一些waring提示
    JavaScript ES6中,export与export default
    git(三):第一次github了解使用
    webstorm(一): 提示css未使用的选择器Selector is never used
    git(二):一些简单入门命令
    git(一):了解、学习、安装git
    关于css虚线
    Mysql聚合函数
    Mysql对用户的操作
  • 原文地址:https://www.cnblogs.com/dbslinux/p/11192712.html
Copyright © 2011-2022 走看看