S
S
sswwssww2020-06-19 10:33:08
Python
sswwssww, 2020-06-19 10:33:08

What is the most accurate way to measure the execution time of a function in Python?

How to accurately calculate the execution time of a function in Python?
Currently I'm using the following decorator:

def timing(f):
    @wraps(f)
    def wrapper(*args, **kwargs)-> str:
        start = monotonic_ns()
        result = f(*args, **kwargs)
        ellapsed_time = monotonic_ns()-start
        return result, ellapsed_time
    return wrapper

- but sometimes it gives 0. Is there a way to measure more accurately?
Interested in the measurement time of the function, not the entire code.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sswwssww, 2020-06-19
@sswwssww

def timing(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        start_time = timeit.default_timer()
        result = f(*args, **kwargs)
        ellapsed_time = timeit.default_timer() - start_time
        return result, ellapsed_time
    return wrapper

D
Dr. Bacon, 2020-06-19
@bacon

Cannot be 0, most likely there is an error somewhere

Y
yamudaqq, 2020-06-19
@yamudaqq

import datetime

start_time = datetime.datetime.now()
*твой код*
print('Время выполнения: ', datetime.datetime.now() - start_time)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question