Search code examples
pythontimecallback

Python time measure function


I want to create a python function to test the time spent in each function and print its name with its time, how i can print the function name and if there is another way to do so please tell me

def measureTime(a):
    start = time.clock() 
    a()
    elapsed = time.clock()
    elapsed = elapsed - start
    print "Time spent in (function name) is: ", elapsed

Solution

  • First and foremost, I highly suggest using a profiler or atleast use timeit.

    However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.

    Python 2:

    def timing(f):
        def wrap(*args):
            time1 = time.time()
            ret = f(*args)
            time2 = time.time()
            print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
            return ret
        return wrap
    

    And the usage is very simple, just use the @timing decorator:

    @timing
    def do_work():
      #code
    

    Python 3:

    def timing(f):
        def wrap(*args, **kwargs):
            time1 = time.time()
            ret = f(*args, **kwargs)
            time2 = time.time()
            print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))
    
            return ret
        return wrap
    

    Note I'm calling f.func_name to get the function name as a string(in Python 2), or f.__name__ in Python 3.