python-函数-装饰器-时间装饰器及应用

版权声明:所有代码均为自己总结,若有雷同请勿模仿 https://blog.csdn.net/weixin_44253023/article/details/89682963
  import time
    
    def decorator(func):
        def wrapper(*args,**kvargs):
            start_time=time.time()#----->函数运行前时间
            func(*args,**kvargs)
            end_time=time.time()#----->函数运行后时间
            cost_time=end_time-start_time#---->运行函数消耗时间
            print("%s消耗时间为%s"%(func.__name__,cost_time))
            return cost_time
        return wrapper#---->装饰器其实是对闭包的一个应用

下面是对装饰器的一个错误应用

import time
    
def decorator(func):
	def wrapper(*args,**kvargs):
		start_time=time.time()#----->函数运行前时间
		func(*args,**kvargs)
		end_time=time.time()#----->函数运行后时间
		cost_time=end_time-start_time#---->运行函数消耗时间
		print("%s消耗时间为%s"%(func.__name__,cost_time))
		return cost_time
	return wrapper#---->装饰器其实是对闭包的一个应用



@decorator
def fibo(n): 
    if n<=0:
        return 0
    elif n==1:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)
		
fibo(100)
fibo(1000)#会报错
#python解析器有递归深度,python3.7.2版本次数为997次,超过递归深度会报错

"""
之所以没有出现预期的结果,因为递归函数每次递归都会调用装饰器,所以会出现
多个结果,当结果大到一定值的时候,就会因为递归深度报错
"""

递归函数也可以间接使用装饰器,一下是装饰器对递归函数的装饰

import time
    
def decorator(func):
	def wrapper(*args,**kvargs):
		start_time=time.time()#----->函数运行前时间
		func(*args,**kvargs)
		end_time=time.time()#----->函数运行后时间
		cost_time=end_time-start_time#---->运行函数消耗时间
		print("%s消耗时间为%s"%(func.__name__,cost_time))
		return cost_time
	return wrapper#---->装饰器其实是对闭包的一个应用


def fibo(n): 
    if n<=0:
        return 0
    elif n==1:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)
        
@decorator		
def main(n):
	return fibo(n)
“”“
对于递归函数,不能直接使用装饰器,而是要把递归函数放到一个函数中,才能间接装饰递归函数
”“”




猜你喜欢

转载自blog.csdn.net/weixin_44253023/article/details/89682963
今日推荐