Last active
April 9, 2018 05:36
-
-
Save ssdemajia/e4e30a1cfc2efa9f03928293159810db to your computer and use it in GitHub Desktop.
计算程序运行时间的装饰器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""time.perf_counter()用于python3,如果实在python2中需要改为time.clock()""" | |
import time | |
import functools | |
def clock(func): | |
@functools.wraps(func) | |
def clocked(*args, **kwargs): | |
t0 = time.perf_counter() | |
result = func(*args) | |
elapsed = time.perf_counter() - t0 | |
name = func.__name__ | |
arg_str = ','.join(repr(arg) for arg in args) | |
kwargs_str = ','.join('%s=%r' % (k, v) for k,v in sorted(kwargs)) | |
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str+','+kwargs_str, result)) | |
return result | |
return clocked | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment