Monday, January 23, 2012

DateTimer: Python class to easily report stop, start and elapsed time


Here is a simple class to make reporting start, finish and elapsed time easy.  If you are running python scripts at command line, this utility will make it easier to keep track of the progress of your processing.
Here is an example of usage:
from arcpyh import DateTimer
import time

timer = DateTimer()
timer.start()
time.sleep(10)
timer.stop()
Here is an example of the output:
Started: 2012-01-23 14:50:00
Finished: 2012-01-23 14:50:10 (Elapsed: 0:00:10)
Here is the important code.  Save this in a file called “arcpyh.py” and put it in the same directory of the script you are running or elsewhere in your pythonpath.
from datetime import datetime

class DateTimer:
    ''' Handy timer that reports start time, end time and delta time

        report:(default=True) If True, prints automatically

        Example output:

            Started: 2012-01-23 14:40:37
            Finished: 2012-01-23 14:40:47 (Elapsed: 0:00:10)

    '''

    NO_START_MSG = "Timer was never started."
    FINISH_MSG = "Finished: {0} (Elapsed: {1})"
    START_MSG = "Started: {0}"

    def __init__(self, report=True):

        self.report = report
        self.startDateTime = None
        self.endDateTime = None
        self.deltaTime = None

    def start(self):

        self.__init__(self.report)
        self.startDateTime = datetime.now()
        self.endDateTime = None

        if self.report:
            self.printStart()

    def stop(self):
        self.endDateTime = datetime.now()
        if self.startDateTime:
            self.deltaTime = self.endDateTime - self.startDateTime

        if self.report:
            self.printEnd()

    def printStart(self):
        if self.startDateTime:
            print self.START_MSG.format(self.datetimeToString(self.startDateTime))
        else:
            print self.NO_START_MSG

    def printEnd(self):
        if self.deltaTime:
            print self.FINISH_MSG.format(self.datetimeToString(self.endDateTime), self.deltaToString(self.deltaTime))
        else:
            print self.NO_START_MSG

    def datetimeToString(self, dateTimeObject):
        return str(dateTimeObject).split(".")[0]

    def deltaToString(self, delta):
        return str(delta).split(".")[0]

No comments:

Post a Comment