定義一個類裝飾器函數(默認用*args, **kwargs表示不定長參數)
# !usr/bin/python3
# -*- coding=utf-8 -*-
class Exectime():
def __init__(self, unit: str = 's', e_time: int = None,):
self.unit = unit
self.e_time = e_time
self.str_f = ''
def __call__(self, func):
def wrapper(*args, **kwargs):
import time as t
start_time = t.time()
res = func(*args, **kwargs)
end_time = t.time()
exec_time = self.e_time or end_time - start_time
# exec_time *= 1000
symbols = {'m': 'Minute', 'h': 'Hour', 'd': 'Day'}
sy_time = {"Minute": 60, "Hour": 3600, "Day": 86400}
try:
if symbols[self.unit]:
if symbols[self.unit] == "Minute":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Minute"
elif symbols[self.unit] == "Hour":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Hour"
elif symbols[self.unit] == "Day":
exec_time = exec_time/sy_time["Minute"] if exec_time >= sy_time["Minute"] else exec_time
unit_f = "Day"
except:
unit_f = "Second"
print("FuncName: {} ==> Exec: {:g} {}!\n".format(func.__name__, exec_time, unit_f))
return res
return wrapper
if __name__ == "__main__":
@Exectime()
def test():
print("This is Test() !!!")
for i in range(5000000):
i += i * i
test()
import random
# 在0-20000數字之間隨機取8000個整數組成一個列表,並對其使用冒泡排序
n = [i for i in range(20000)]
arr = random.sample(n, 8000)
@Exectime()
def bubble_sort(arr):
for i in range(len(arr) - 1, 0, -1):
for j in range(i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
bubble_sort(arr)
執行效果:
C:\Users\Admin\AppData\Local\Programs\Python\Python38\python.exe D:/pythontest/99-test/111.py
This is Test() !!!
FuncName: test ==> Exec: 849.727 Second!
FuncName: bubble_sort ==> Exec: 10462 Second!
Process finished with exit code 0