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函数就叫一装饰器!!
  • 相关阅读:
    Linux防火墙开放某端口号
    MySQL的权限管理
    Linux安装Node.js
    Eclipse上传新项目到GitLab
    Linux安装Nexus
    Linux安装中文字体_宋体
    Linux用户管理
    Linux安装MySQL_5.6
    reduce基本用法,js实现分组
    js 数字格式化
  • 原文地址:https://www.cnblogs.com/dbslinux/p/11192712.html
Copyright © 2011-2022 走看看