[PYTHON] Stopwatch

A little exercise. If you want to add a function, you can add it as much as you want, but it is not necessary, so at least. The problem with Temp is that it takes a little time for internal processing, but there is no motivation to improve it.

import time

class StopWatchLite(object):

    def __init__(self) :
        self.make = time.time()
        return

    def start(self) :
        self.st = time.time()
        return self

    def stop(self) :
        return time.time()-self.st

    def reset(self) :
        self.st = self.make
        return self

    def __str__(self) :
        return str( self.stop() )



class StopWatchTemp(object):
    """
    this can stop counting time temporally.
    """
    def __init__( self, verbose=0) :
        self.make = time.time()
        self.stac = []
        self.stat = "standby"
        self.verbose = verbose
        return

    def start(self) :
        self.stac = []
        self.stat = "running"
        self.st = time.time()
        return self

    def stop(self) :
        (self.stac).append( time.time() - self.st )
        self.stat = "stopped"
        return sum( _ for _ in self.stac )

    def reset(self) :
        self.st = self.make
        self.stat = "standby"
        self.stac = []
        return self

    def restart(self) :
        if   self.stat == "stopped" :
            self.stat = "running"
            self.st = time.time()
        elif self.stat == "standby" :
            if self.verbose >= 2 :
                print "start->stop->restart"
            if self.verbose >= 1 :
                print "regarding 'restart' as 'start'."
            return self.start()
        elif self.stat == "running" :
            if self.verbose >= 2 :
                print "start->stop->restart"
            if self.verbose >= 1 :
                print "regarding 'restart' as 'reset' and 'start'."
            return self.reset().start()

    def __str__(self) :
        return str( stop() )

def test():

    def wast_function(n):
        [ i for i in xrange(n) ]

    s = StopWatchLite()

    s.start()
    wast_function(1000000)
    t1 = s.stop()

    s.start()
    wast_function(1000000)
    t2 = s.stop()

    print t1,t2

    s = StopWatchTemp()

    s.start()
    wast_function(1000000)
    s.stop()

    s.restart()
    wast_function(1000000)
    t1 = s.stop()

    print t1

if __name__ == "__main__" :
    test()

Recommended Posts

Stopwatch
It's a stopwatch