konvertieren Ich kann nicht für das Leben von mir herauszufinden, wie man dies zu einem Dekorateur. Jede Hilfe oder ein Beispiel wäre genial. HierPython: Wie kann ich dies in einen Dekorateur
ist der Code
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
Hier ist ein Beispiel
.. 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
Überprüfen Sie dies [post] (https://Stackoverflow.com/a/44846831/6655211) – PRMoureu
Haben Sie über die Verwendung des 'timeit'-Moduls nachgedacht? – cmd