Search code examples
pythontimertime-tracking

how to implement a interface to keep track of runtime of each sub-sections and also the total run time of the section in python


is there any one know about: how to design a interface in python so that for the caller, it can track where time is being spent between two points in a piece of code?

For example: if we have several pieces of code we labeled them as A, B, C, D, so how could we track the runtime of these pieces and also about the runtime of the total piece of code?


Solution

  • This sounds like something that you could make good use of a decorator for something like the entryExit decorator could log the time spent inside each decorated function:

    class entryExit(object):
    
        def __init__(self, f):
            self.f = f
    
        def __call__(self):
            print "Entering", self.f.__name__
            self.f()
            print "Exited", self.f.__name__
    
    @entryExit
    def func1():
        print "inside func1()"
    
    @entryExit
    def func2():
        print "inside func2()"