对python程序代码做计时统计

对python程序代码做计时统计

#-*-coding:utf-8-*-
#@author    :vict
#@Time      :2020-11-02 17:01
#@File      :tmie_count
#@software  :PyCharm
# 统计耗时
from time import clock
from time import perf_counter
from time import sleep

#方式1 --》使用clock()
# DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
# Python time.clock在Python3.3废弃,在Python3.8中将被移除

#方式2 --》使用perf_counter()
def time_test():
    start = perf_counter()
    sleep(2)
    end = perf_counter()
    print('{}.{} : {} second'.format(time_test.__module__, time_test.__name__, end - start))

time_test()

#方式3 --》使用装饰器
from functools import wraps
def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = perf_counter()
        r = func(*args, **kwargs)
        end = perf_counter()
        print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
        return r
    return wrapper

@timethis
def time_test1():
    sleep(2)

time_test1()
原文地址:https://www.cnblogs.com/huanyinglvtuan/p/13915412.html