用装饰器计算函数运行时间

#!/user/bin/python
# -*- coding:utf-8 -*-
#1、
# l = [1,3]
# a = l.__iter__() #就等于iter(l)
# print(a.__next__())
# print(a.__next__())
#2、装饰器本质就是函数,功能是为其他函数添加附加功能,原则:不修改被修饰函数的源代码,不修改被装饰函数的调用方式
# import time
# def timmer(func):
# def wapper(*args,**kwargs):
# start_time = time.time()
# res = func(*args,**kwargs)
# stop_time = time.time()
# print("函数运行时间是%s" %(stop_time - start_time))
# return res
# return wapper
# @timmer
# def cal(l):
# res = 0
# for i in l:
# time.sleep(0.1)
# res += i
# return res
# res = cal(range(20))
# print(res)
# print("结束了。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。")
#3、装饰器 = 高阶函数 + 嵌套函数 + 闭包
#4、高阶函数:函数接收的参数是一个函数名,函数的返回值是一个函数名,
# def foo():
# print("你好啊张师傅")
# def test(func):
# print(func) #这个是打印func的内存地址
# start_time = time.time()
# time.sleep(2)
# func()
# stop_time = time.time()
# print("运行时间是%s" %(stop_time - start_time))
# test(foo)
#5、
# def foo():
# print("from the foo")
# def test(func):
# return func
# res = test(foo)
# print(res)
# res()
# foo = test(foo)
# print(foo)
# foo()
#6、
# import time
# # def foo():
# # time.sleep(3)
# # print("来自 foo")
# # #不修改foo源代码、不修改foo的调用方式
# # def timmer(func):
# # start_time = time.time()
# # func()
# # stop_time = time.time()
# # print("函数运行时间是%s" %(stop_time - start_time))
# # return func
# # foo = timmer(foo)
# # foo()
#7、
# def father(name):
# print("from father%s" %name)
# def son():
# print("from son")
# def grandson():
# print("from grandson")
# grandson()
# son()
# father("zd")
# print("上面运行结束。。。。。。。。。。。。")
# def father(auth_type):
# # print("from father%s" %name)
# def son():
# name = "zs"
# print("我的爸爸是%s" %auth_type)
# # print(locals()) #locals是打印当前层的局部变量
# son()
# father("zd")
#8、装饰器框架
import time
def timmer(func):
def wrapper(*args,**kwargs): #*args代表把所有的位置参数接收成元组、**kwargs代表用户传值的时候可能是关键字
# print(func)
start_time = time.time()
res = func(*args,**kwargs) #就是在运行test
stop_time = time.time()
print("运行时间是%s" %(stop_time - start_time))
return res
return wrapper #最后再返回结束状态
@timmer #等同于test = timmer(test)
def test(name,age):
time.sleep(3)
print("test函数运行完毕,名字是【%s】 年龄是【%s】" %(name,age))
return "这是test的返回值"
@timmer
def test1(name,age,gender):
time.sleep(1)
print("test1函数运行完毕,名字是【%s】 年龄是【%s】 性别是【%s】" %(name,age,gender))
return "这是test1的返回值"
# res = timmer(test) #返回的是wrapper地址
# res() #执行的是wrapper()
# test = timmer(test)
# test()
res = test("linhaifeng",18) #就是在运行wrapper
# print(res)
test1("alex",18,"male")
#9、
# def test1():
# time.sleep(3)
# print("test函数运行完毕")
# return "嘿嘿和"
# res = test1() #加括号只是调用、加括号后并赋值打印后才是函数的返回值、默认是None、也可以定义return 加字符串或列表或其他值、return应写在当前函数里面
# print(res)

猜你喜欢

转载自www.cnblogs.com/zhang-da/p/10972906.html