Get time of execution of a block of code in Python 2.7 Get time of execution of a block of code in Python 2.7 python python

Get time of execution of a block of code in Python 2.7


To get the elapsed time in seconds, you can use timeit.default_timer():

import timeitstart_time = timeit.default_timer()# code you want to evaluateelapsed = timeit.default_timer() - start_time

timeit.default_timer() is used instead of time.time() or time.clock() because it will choose the timing function that has the higher resolution for any platform.


I always use a decorator to do some extra work for a existing function, including to get the execution time. It is pythonic and simple.

import timedef time_usage(func):    def wrapper(*args, **kwargs):        beg_ts = time.time()        retval = func(*args, **kwargs)        end_ts = time.time()        print("elapsed time: %f" % (end_ts - beg_ts))        return retval    return wrapper@time_usagedef test():    for i in xrange(0, 10000):        passif __name__ == "__main__":    test()


You can achieve this through the Context Manager, for example:

from contextlib import contextmanagerimport timeimport logging@contextmanagerdef _log_time_usage(prefix=""):    '''log the time usage in a code block    prefix: the prefix text to show    '''    start = time.time()    try:        yield    finally:        end = time.time()        elapsed_seconds = float("%.2f" % (end - start))        logging.debug('%s: elapsed seconds: %s', prefix, elapsed_seconds)

use example:

with _log_time_usage("sleep 1: "):    time.sleep(1)