Skip to content

Instantly share code, notes, and snippets.

@kangzhiheng
Last active August 20, 2020 11:54
Show Gist options
  • Save kangzhiheng/a201a0bb716507877c281bef01d6a5f4 to your computer and use it in GitHub Desktop.
Save kangzhiheng/a201a0bb716507877c281bef01d6a5f4 to your computer and use it in GitHub Desktop.
Python装饰器-定时
# coding:utf-8
from functools import wraps
from datetime import datetime
import time
def func_timer(function):
'''
用装饰器实现函数计时
:param function: 需要计时的函数
:return: None
'''
@wraps(function)
def function_timer(*args, **kwargs):
print('[Function: {name} start: {time}]'.format(name = function.__name__, time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
t0 = datetime.now()
result = function(*args, **kwargs)
t1 = datetime.now()
print('[Function: {name} finished, {time}, spent time: {cost:.2f}s]'.format(name = function.__name__, time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), cost = (t1 - t0).seconds))
return result
return function_timer
@func_timer
def test(x,y):
s = x + y
time.sleep(10.8)
print('the sum is: {0}'.format(s))
if __name__ == '__main__':
test(1,2)
# 输出结果
'''
[Function: test start...]
the sum is: 3
[Function: test finished, spent time: 1.50s]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment