FW: updated timer

Terry Disz disz at mcs.anl.gov
Fri Aug 29 14:34:53 CDT 2003


AG-DEV,

Here is a timer module Rusty and I are using to instrument our code and
find out what is taking how much time.

If anyone  cares to time something, you might be interested in it.

A new version with std deviation is forthcoming, I will post when ready.


Terry

-----Original Message-----
From: Rusty Lusk [mailto:lusk at mcs.anl.gov] 
Sent: Thursday, August 28, 2003 10:43 AM
To: desai at mcs.anl.gov; rbutler at mcs.anl.gov; rbutler at mtsu.edu;
disz at mcs.anl.gov; bradshaw at mcs.anl.gov; alusk at uiuc.edu
Subject: updated timer

This version has a check() method to see how much time a running timer
has accumulated (feature requested by Narayan), and raises an exception
if you try to check a timer that is not running.


#!/usr/bin/env python

# A timer class

from time import time
from exceptions import Exception

class timer_exception(Exception):
    pass 

class timer:
    def __init__(self,name):

        self.num_intervals = 0
        self.total_time    = 0
        self.name          = name
        self.min           = 1000000
        self.max           = 0
        self.starttime     = -1

    def start(self):
        self.starttime = time()

    def stop(self):
        self.stoptime = time()
        self.new_interval = self.stoptime - self.starttime
        self.total_time += self.new_interval
        self.num_intervals += 1
        self.avg_interval = self.total_time / self.num_intervals
        if self.new_interval < self.min:
            self.min = self.new_interval
        if self.new_interval > self.max:
            self.max = self.new_interval
        self.starttime = -1               # reset

    def check(self):
        if self.starttime == -1:
            raise timer_exception
        else:
            return time() - self.starttime

    def tprint(self):
        print 'statistics for %s timer:' % (self.name)
        print 'total time          = %6.3f seconds' % (self.total_time)
        print 'number of intervals =  %s' % (self.num_intervals)
        print 'average interval    = %6.3f seconds' %
(self.avg_interval)
        print 'max interval        = %6.3f seconds' % (self.max)
        print 'min interval        = %6.3f seconds' % (self.min)

# a test program

if __name__ == '__main__':

    kbd_timer = timer('keyboard')

    for i in range(5):
        kbd_timer.start()
        line = raw_input("Type a line: ")
        kbd_timer.stop()
        print 'Typed %s in %f seconds' % (line, kbd_timer.new_interval)

    kbd_timer.tprint() 




More information about the ag-dev mailing list