Small Exercise 2

# 1 test function execution time decorator exemplary 
Import Time
 DEF timing_func (fn):
     DEF warpper (): 
        Start = the time.time () 
        fn ()    # perform incoming parameter fn 
        STOP = the time.time ()
         return (STOP - Start)
     return warpper 
@timing_func 
DEF test_list_append (): 
    LST = []
     for I in Range (0,100000 ): 
        lst.append (I)   
@timing_func 
DEF test_list_compre (): 
    [I for Iin Range (0,100000)]   # listing formula 
A = test_list_append () 
C = test_list_compre ()
 Print ( " Test the append Time List: " , A)
 Print ( " Test List comprehensions Time: " , C)
 Print ( " the append / COMPRE: " , round (a / c, 3 )) 

the Test List the append time: .0219423770904541 
the Test List comprehensions time: 0.007980823516845703 
the append / COMPRE: 2.749 

2. statistical abnormal occurrences and time decorator
write a decorator, a statistical when an exception specified number of repeated, long-time experience.
import time
import math


def excepter(f):
    i = 0 t1 = time.time() def wrapper(): try: f() except Exception as e: nonlocal i i += 1 print(f'{e.args[0]}: {i}') t2 = time.time() if i == n: print(f'spending time:{round(t2-t1,2)}') return wrapper

3.定制递减迭代器
# Write an iterator, by loop, in descending order to achieve a positive integer of 1, until of 0. The
 class the Descend ( the Iterator): DEF the __init __ ( Self, N): self.n = N self.a = 0 DEF the __iter__ ( Self): return Self DEF the __next __ ( Self): the while self.a < self.n: self.n - = . 1 return self.n The raise the StopIteration descend_iter = the Descend ( 10) Print ( List (descend_iter)) [ . 9, . 8 , 7, 6, 5, 4,3, 2, 1, 0]

 

Guess you like

Origin www.cnblogs.com/miaoweiye/p/12613679.html