Measuring elapsed time with the Time module Measuring elapsed time with the Time module python python

Measuring elapsed time with the Time module


start_time = time.time()# your codeelapsed_time = time.time() - start_time

You can also write simple decorator to simplify measurement of execution time of various functions:

import timefrom functools import wrapsPROF_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_profilingdef 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' % (max_time, avg_time)def clear_prof_data():    global PROF_DATA    PROF_DATA = {}

Usage:

@profiledef your_function(...):    ...

You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():


time.time() will do the job.

import timestart = time.time()# run your codeend = time.time()elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.


For users that want better formatting,

import timestart_time = time.time()# your scriptelapsed_time = time.time() - start_timetime.strftime("%H:%M:%S", time.gmtime(elapsed_time))

will print out, for 2 seconds:

'00:00:02'

and for 7 minutes one second:

'00:07:01'

note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:

import datetimestart = datetime.datetime.now()# some codeend = datetime.datetime.now()elapsed = end - startprint(elapsed)# orprint(elapsed.seconds,":",elapsed.microseconds) 

strftime documentation