Skip to content

Instantly share code, notes, and snippets.

@feiandxs
Created June 29, 2022 09:23
Show Gist options
  • Save feiandxs/c8694a43892657109957c937291e6735 to your computer and use it in GitHub Desktop.
Save feiandxs/c8694a43892657109957c937291e6735 to your computer and use it in GitHub Desktop.
timer.py
'''
Date: 2022-06-01 13:49:12
LastEditors: ibegyourpardon
LastEditTime: 2022-06-01 13:52:47
FilePath: /undefined/Users/feiandxs/Downloads/timer.py
'''
import time
class TimerError(Exception):
"""
A custom exception class that is raised when the timer has been
stopped.
"""
pass
class Timer:
def __init__(self):
self.start_time = None
self.stop_time = None
def start(self):
"""Start a new timer"""
if self.start_time:
raise TimerError("Timer has already been started,Use .stop() to stop it")
self.start_time = time.perf_counter()
def stop(self):
"""Stop the timer ,and report the elapsed time"""
if not self.start_time:
raise TimerError("Timer has not been started,Use .start() to start it")
elapsed_time = time.perf_counter() - self.start_time
self.start_time = None
print(f"Elapsed time: {elapsed_time:0.4f} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment