With the Time module in python is it possible to measure elapsed time? If so, how do I do that?
I need to do this so that if the cursor has been in a widget for a certain duration an event happens.
With the Time module in python is it possible to measure elapsed time? If so, how do I do that?
I need to do this so that if the cursor has been in a widget for a certain duration an event happens.
start_time = time.time()
# your code
elapsed_time = time.time() - start_time
You can also write simple decorator to simplify measurement of execution time of various functions:
import time
from functools import wraps
PROF_DATA = {}
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = time.time() - start_time
if fn.__name__ not in PROF_DATA:
PROF_DATA[fn.__name__] = [0, []]
PROF_DATA[fn.__name__][0] += 1
PROF_DATA[fn.__name__][1].append(elapsed_time)
return ret
return with_profiling
def print_prof_data():
for fname, data in PROF_DATA.items():
max_time = max(data[1])
avg_time = sum(data[1]) / len(data[1])
print "Function %s called %d times. " % (fname, data[0]),
print 'Execution time max: %.3f, average: %.3f' % (avg_time, max_time)
def clear_prof_data():
global PROF_DATA
PROF_DATA = {}
Usage:
@profile
def your_function(...):
...
You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():