Skip to content

Latest commit

 

History

History
49 lines (39 loc) · 957 Bytes

136.md

File metadata and controls

49 lines (39 loc) · 957 Bytes
@author jackzhenguo
@desc
@tag decorator
@version 
@date 2020/02/03

136 测试函数运行时间的装饰器

#测试函数执行时间的装饰器示例
import time
def timing_func(fn):
    def wrapper():
        start=time.time()
        fn()   #执行传入的fn参数
        stop=time.time()
        return (stop-start)
    return wrapper

使用装饰器:

@timing_func
def test_list_append():
    lst=[]
    for i in range(0,100000):
        lst.append(i)  
@timing_func
def test_list_compre():
    [i for i in range(0,100000)]  #列表生成式
    
a=test_list_append()
c=test_list_compre()

print("test list append time:",a)
print("test list comprehension time:",c)
print("append/compre:",round(a/c,3))

#test list append time: 0.0219423770904541
#test list comprehension time: 0.007980823516845703
#append/compre: 2.749
[上一个例子](135.md) [下一个例子](137.md)