How do I get time of a Python program's execution?

后端 未结 30 1680
甜味超标
甜味超标 2020-11-22 02:20

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I\'ve looked at the timeit

30条回答
  •  一生所求
    2020-11-22 02:59

    I liked Paul McGuire's answer too and came up with a context manager form which suited my needs more.

    import datetime as dt
    import timeit
    
    class TimingManager(object):
        """Context Manager used with the statement 'with' to time some execution.
    
        Example:
    
        with TimingManager() as t:
           # Code to time
        """
    
        clock = timeit.default_timer
    
        def __enter__(self):
            """
            """
            self.start = self.clock()
            self.log('\n=> Start Timing: {}')
    
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            """
            """
            self.endlog()
    
            return False
    
        def log(self, s, elapsed=None):
            """Log current time and elapsed time if present.
            :param s: Text to display, use '{}' to format the text with
                the current time.
            :param elapsed: Elapsed time to display. Dafault: None, no display.
            """
            print s.format(self._secondsToStr(self.clock()))
    
            if(elapsed is not None):
                print 'Elapsed time: {}\n'.format(elapsed)
    
        def endlog(self):
            """Log time for the end of execution with elapsed time.
            """
            self.log('=> End Timing: {}', self.now())
    
        def now(self):
            """Return current elapsed time as hh:mm:ss string.
            :return: String.
            """
            return str(dt.timedelta(seconds = self.clock() - self.start))
    
        def _secondsToStr(self, sec):
            """Convert timestamp to h:mm:ss string.
            :param sec: Timestamp.
            """
            return str(dt.datetime.fromtimestamp(sec))
    

提交回复
热议问题