Python计时装饰器,可用于给函数运行时间计时,进而进行性能优化

from functools import wraps
import time

def timing(func):
    """
    计时装饰器
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        """
        装饰函数
        """
        start = time.clock()
        r = func(*args, **kwargs)
        end =time.clock()
        print('[' + func.__name__ + ']used:' + str(end - start))
        return r
    return wrapper

使用方法:

@timing
def func():
    """
    耗时操作
    """
    return


欢迎关注我的微信公众号
![](http://upload-images.jianshu.io/upload_images/3093748-7c07998b7495defc.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)