【发布时间】:2017-07-20 19:58:10
【问题描述】:
我一辈子都想不通如何把它变成一个装饰器。 任何帮助或示例都会很棒。
这里是代码
import datetime
def time_func(function, *args, **kwargs):
'''
Add the execution time to a functions attributes
'''
# Start the clock.
start = datetime.datetime.now()
# Execute the function and record the results.
function_result = function(*args, **kwargs)
# Calculate the elapsed time and add it to the function
# attributes.
function.elapsed = datetime.datetime.now() - start
# Returned the function with the added elapsed attribute
return function_result
这是一个使用示例
.. import datetime
..
..
.. def time_func(function, *args, **kwargs):
.. '''
.. Add the execution time to a functions attributes
.. '''
.. # Start the clock.
.. start = datetime.datetime.now()
.. # Execute the function and record the results.
.. function_result = function(*args, **kwargs)
.. # Calculate the elapsed time and add it to the function
.. # attributes.
.. function.elapsed = datetime.datetime.now() - start
.. # Returned the function with the added elapsed attribute
.. return function_result
..
..
.. def f(name):
.. print name
..
.. time_func(f, 'foo')
.. print f.elapsed
..
foo
0:00:00.000115
【问题讨论】:
-
查看post
-
您是否考虑过使用
timeit模块?
标签: python performance time