File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+
3+ ``` python
4+ # 测试函数执行时间的装饰器示例
5+ import time
6+ def timing_func (fn ):
7+ def wrapper ():
8+ start= time.time()
9+ fn() # 执行传入的fn参数
10+ stop= time.time()
11+ return (stop- start)
12+ return wrapper
13+ @timing_func
14+ def test_list_append ():
15+ lst= []
16+ for i in range (0 ,100000 ):
17+ lst.append(i)
18+ @timing_func
19+ def test_list_compre ():
20+ [i for i in range (0 ,100000 )] # 列表生成式
21+ a= test_list_append()
22+ c= test_list_compre()
23+ print (" test list append time:" ,a)
24+ print (" test list comprehension time:" ,c)
25+ print (" append/compre:" ,round (a/ c,3 ))
26+ # @timing_func修饰test_list_append意味着完成两部操作,将test_list_append作为timing_func()的参数即执行timing_func(test_list_append),然后将test_list_append替换成timing_func()返回的结果。
27+ # 即被修饰的函数总是被替换成@符号所引用的函数返回值。
28+ ```
29+
30+ test list append time: 0.0219423770904541
31+ test list comprehension time: 0.007980823516845703
32+ append/compre: 2.749
33+
You can’t perform that action at this time.
0 commit comments