tic, toc functions analog in Python
Question: What is the best analog of MATLAB tic and toc functions (
<http://www.mathworks.com/help/techdoc/ref/tic.html>) in Python?


Answer: Apart from `timeit` which ThiefMaster mentioned, a simple way to do it is just
(after importing `time`):

    
    
    t = time.time()
    # do stuff
    elapsed = time.time() - t
    

I have a helper class I like to use:

    
    
    class Timer(object):
        def __init__(self, name=None):
            self.name = name
    
        def __enter__(self):
            self.tstart = time.time()
    
        def __exit__(self, type, value, traceback):
            if self.name:
                print '[%s]' % self.name,
            print 'Elapsed: %s' % (time.time() - self.tstart)
    

It can be used as a context manager:

    
    
    with Timer('foo_stuff'):
       # do some foo
       # do some stuff
    

Sometimes I find this technique more convenient than `timeit` \- it all
depends on what you want to measure.

