Skip to content

Instantly share code, notes, and snippets.

@Ashwinning
Last active December 27, 2020 00:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ashwinning/313a4bed6af3f7599ac168c4de82b555 to your computer and use it in GitHub Desktop.
Save Ashwinning/313a4bed6af3f7599ac168c4de82b555 to your computer and use it in GitHub Desktop.
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

# Manual: http://hacks.ash.wine/super-simple-python-timer/
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
@adeebx1
Copy link

adeebx1 commented Apr 28, 2018

Hello
i got this error when trying to get the time
<bound method Timer.get_time of <Timer.Timer object>>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment