Measuring response time between tasks

I am coding a program (in Python) that returns me some data. I want to know how to measure the response time between request and response (for performance analysis), then I will store this somewhere.

Is there a better and effective way to do this or simply insert, for example, time.ctime()before the request and the other time.ctime()after the answer, and then subtract them? How:

pre_time = time.ctime()
a = x + y
print a
pos_time = time.ctime()
result_time = postime - pretime

Of course, this subtraction will not work, but it is just for reference.
Thank!

+4
source share
1 answer

The easiest solution is to write a decorator that does the same.

import time

def compute_time(func):
     def wrapper(*args, **kwargs):
         start = time.time()
         result = func(*args, **kwargs)
         time_taken = time.time() - start

         print("Function {0}: {1} seconds".format(func.func_name, time_taken)) 
         # Or you can place a logger here too.

         return result

     return wrapper

@compute_time
def add(x, y):
    return x + y

, - - , timeit.

+7

Source: https://habr.com/ru/post/1680493/


All Articles