3/5/18

Python Class: ElapsedTime (works like a stopwatch)

 If you are learning python, short examples are always helpful. Here is one.

Class in Python: ElapsedTime:

Use:

e1 = ElapsedTime()  # starts time e1

x = e1()  # get elapsed time as float in seconds from timer

... do something more

x = e1()  # get elapsed time since start

The code shows a couple neat things in python:
  • using a object reference as a methods by defining the __call__ standard method
  • using a Unicode char in output (this is easier in python 3)

The Code:

 
"""Small elapsed time class"""
# YouTube subscribe link: https://goo.gl/ZgZrZ5
# Gerry Jenkins

import time

class ElapsedTime():
    """elapsed since creation objects"""

    def __init__(self):
                self.start = time.time()  # store only start time
        
    def __call__(self):  # used to use object name as call
        """return elapsed time in float seconds"""
        return time.time() - self.start
        
        
if __name__ == "__main__":
    # check it out, follow two elapsed timers
    
    e1 = ElapsedTime()
    for _ in range(5):  # use e1
        print(f'e1: {e1()*1000000:0.1f} µsecs') # unicode micro
        
    e2 = ElapsedTime()
    for _ in range(5):  # use both e1 and e2
        print(f'e1: {e1()*1000000:0.1f} | e2: {e2()*1000000:0.1f}')

        

OH, and please subscribe to my YouTube Channel at: youtube.com/gjenkinslbcc

And check out my Python, Data Structures and Algorithms video class

No comments:

Post a Comment

Please comment or give suggestions for follow up articles