Pythonクラスデコレータはタイマー@timerを実装します

Pythonの一般的な操作

クラスデコレータ

タイマー

各関数の実行時間をカウントするには、クラスデコレータをタイマーとして設計し、使用するたびに関数の直前で宣言します。
一般的なタイマーは次のとおりです。関数の前で@timerを宣言するだけです。

# This is for timing
def timer(func):
    def func_wrapper(*args,**kwargs):
        from time import time
        time_start = time()
        result = func(*args,**kwargs)
        time_end = time()
        time_spend = time_end - time_start
        print('\n{0} cost time {1} s\n'.format(func.__name__, time_spend))
        return result
    return func_wrapper

使用する場合は、関数定義のすぐ上に@timerを記述します

@timer
def test():
	print("hello world!")

おすすめ

転載: blog.csdn.net/qq_32507417/article/details/107084319