Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Super Simple Python Timer #gistblog #python

Super Simple Python Timer

Timer module for python to measure elapsed time.

Import

Copy Timer.py to the same folder as your python files.

Linux

wget "https://gist.githubusercontent.com/Ashwinning/313a4bed6af3f7599ac168c4de82b555/raw/Timer.py"

Windows

Invoke-WebRequest https://gist.githubusercontent.com/Ashwinning/313a4bed6af3f7599ac168c4de82b555/
raw/Timer.py -OutFile Timer.py

Usage

from Timer import Timer
timer = Timer() #Initialize the timer
#wash clothes for 5 seconds
timer.print_time() #Print the time elapsed since Initialization (in seconds)
#dry clothes for 3 seconds
timer.print_new_time() #Print the time elapsed since Initialization and reset the timer
#burn clothes for 10 seconds
print (str('Burnt clothes for ' + str(timer.get_time() + ' seconds.')))

Output

>>> 5
>>> 8
>>> Burnt clothes for 10 seconds.

API

  • get_time()

    Returns the time elapsed (Does not reset the counter).

  • get_new_time()

    Returns the time elapsed and resets the counter.

  • print_time()

Prints the time elapsed (Does not reset the counter).

  • print_new_time()

Prints the time elapsed and resets the counter.

  • get_time_hhmmss()

    Returns the time elapsed in HH:mm:ss (Does not reset the counter).

Acknowledgements

Forked from code at http://stackoverflow.com/a/35199035/2899995

import time
class Timer:
def __init__(self):
self.start = time.time()
'''
Restarts the timer.
'''
def restart(self):
self.start = time.time()
'''
Returns the time elapsed and resets the counter.
'''
def get_new_time(self):
value = time.time() - self.start
self.restart()
return value
'''
Prints the time elapsed and resets the counter.
'''
def print_new_time(self):
print (self.get_new_time())
'''
Returns the time elapsed (Does not reset the counter).
'''
def get_time(self):
return time.time() - self.start
self.restart()
'''
Prints the time elapsed (Does not reset the counter).
'''
def print_time(self):
print(get_time)
'''
Returns the time elapsed in HH:mm:ss (Does not reset the counter).
'''
def get_time_hhmmss(self):
end = time.time()
m, s = divmod(end - self.start, 60)
h, m = divmod(m, 60)
time_str = "%02d:%02d:%02d" % (h, m, s)
return time_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment