python 装饰器进行函数运行时间统计

示例:

 1 # encoding="utf-8"
 2 
 3 import os
 4 import random
 5 import shutil
 6 import time
 7 import subprocess
 8 from functools import wraps
 9 
10 
11 def print_run_time(func):
12     @wraps(func)
13     def wrapper(*args, **kw):
14         start_time = time.time()
15         result = func(*args, **kw)
16         end_time = time.time()
17         print("函数的运行时间(s):{}".format(end_time - start_time))
18         print("函数的运行时间(ms):{}".format(float(end_time - start_time) * 1000.0))
19         return result
20 
21     return wrapper
22 
23 
24 @print_run_time
25 def sum():
26     a = 1 + 2
27     print(a)

 

posted @ 2022-07-06 16:38  小嘉欣  阅读(442)  评论(0编辑  收藏  举报