Skip to content

Instantly share code, notes, and snippets.

@gerryjenkinslb
Last active March 6, 2018 22:29
Show Gist options
  • Save gerryjenkinslb/057b61318675fa0523e7be27604d7dde to your computer and use it in GitHub Desktop.
Save gerryjenkinslb/057b61318675fa0523e7be27604d7dde to your computer and use it in GitHub Desktop.
Python3 elapsed time implementations in Class, Generator, and Functions for discussion and education
# elapsed timer: as generator
# Youtube subscribe link: https://goo.gl/ZgZrZ5
# Gerry Jenkins
import time
class ElapsedTime():
def __init__(self):
# store only start time
self.start = time.time()
def __call__(self):
return time.time() - self.start
if __name__ == "__main__":
e1 = ElapsedTime()
for _ in range(5):
print(f'e1: {e1()*1000000:0.1f} µsecs')
e2 = ElapsedTime()
for _ in range(5):
print(f'e1: {e1()*1000000:0.1f} | e2: {e2()*1000000:0.1f}')
# elapsed timer: functional
# Youtube subscribe link: https://goo.gl/ZgZrZ5
# Gerry Jenkins
import time
def elapsed_timer():
start = time.time()
return lambda : time.time() - start
if __name__ == "__main__":
e1 = elapsed_timer()
for _ in range(5):
print(f'e1: {e1()*1000000:0.1f} µsecs')
e2 = elapsed_timer()
for _ in range(5):
print(f'e1: {e1()*1000000:0.1f} | e2: {e2()*1000000:0.1f}')
# elapsed timer: as generator
# Youtube subscribe link: https://goo.gl/ZgZrZ5
# Gerry Jenkins
import time
def elapsed_time():
start = time.time()
while 1:
yield time.time() - start
if __name__ == "__main__":
e1 = elapsed_time()
for _ in range(5): # use e1
print(f'e1: {next(e1)*1000000:0.1f} µsecs') # unicode micro
e2 = elapsed_time()
for _ in range(5): # use both e1 and e2
print(f'e1: {next(e1)*1000000:0.1f} | e2: {next(e2)*1000000:0.1f}')
I want to build an elapsed timer 'thing' for a simple game I am doing.
class, generator, or function?
Use:
- create a timer starting at zero
- query the elapsed time since creation at any point after
*** Pleas subscribe to my Youtube Channel: https://goo.gl/ZgZrZ5 ***
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment