Denis Callau
Denis Callau

Reputation: 285

Measuring the response time between tasks

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

There's a better and efficient way to do this or just inserting for example a time.ctime() before the request and another time.ctime() after the answer, then subtract them? Like:

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

Of course this subtraction won't work, but it's just for reference.
Thanks!

Upvotes: 4

Views: 103

Answers (1)

hspandher
hspandher

Reputation: 16743

Easiest solution would be 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

With that said, if your use case is complex - consider some tailor-made solution like timeit.

Upvotes: 7

Related Questions