Python: 使用装饰器“@”取得函数执行时间

class A():

Python: 使用装饰器“@”取得函数执行时间 - oldJ的学习笔记 - 博客频道 - CSDN.NET

Python: 使用装饰器“@”取得函数执行时间

分类: Python 2009-10-14 12:53 752人阅读 评论(0) 收藏 举报

Python中可以使用装饰器对函数进行装饰(或说包装),利用这个特性,可以很方便、简洁地解决一些问题,比如获得函数执行时间的问题。

首先,我们定义一个函数,如下:


[python] view plaincopyprint?

    def exeTime(func): 
        def newFunc(*args, **args2): 
            t0 = time.time() 
            print "@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__) 
            back = func(*args, **args2) 
            print "@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__) 
            print "@%.3fs taken for {%s}" % (time.time() - t0, func.__name__) 
            return back 
        return newFunc 

当然,不要忘了“import time”导入time模块。这个函数就可以用作我们计算函数执行时间的修饰器了。

接下来,我们就可以在需要计时的函数前一行引用它作为装饰,比如:


[python] view plaincopyprint?

    @exeTime 
    def foo(): 
        for i in xrange(10000000): 
            pass 

注意最上方的“@exeTime ”,装饰器的语法以“@”开头,接着是装饰函数,在本例中为“exeTime”。这时,执行函数foo,装饰器就会在控制台打印出这个函数的执行时间了。

完整代码如下:


[python:collapse] + expand sourceview plaincopyprint?

    # -*- coding: utf-8 -*- 
    import time 
     
    # --exeTime 
    def exeTime(func): 
        def newFunc(*args, **args2): 
            t0 = time.time() 
            print "@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__) 
            back = func(*args, **args2) 
            print "@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__) 
            print "@%.3fs taken for {%s}" % (time.time() - t0, func.__name__) 
            return back 
        return newFunc 
    # --end of exeTime 
    
    @exeTime 
    def foo(): 
        for i in xrange(10000000): 
            pass 
     
    if __name__ == "__main__": 
        foo() 

在笔者电脑上的运行结果为:

@13:12:27, {foo} start
@13:12:27, {foo} end
@0.203s taken for {foo}

当然,上面只是一个很简单的示例,事实上,本例中的装饰器exeTime不仅可以装饰类似上面“foo”这样不带参数的函数,也能装饰带任意参数的函数,甚至还可以装饰类的方法,用法与上面是一样的。

除了计算运行时间外,装饰器还可以有很多用途,比如记录运行日志等,更多的用途等待更多的朋友去发掘。
原文地址:https://www.cnblogs.com/lexus/p/2777340.html