Created
June 29, 2022 09:23
-
-
Save feiandxs/c8694a43892657109957c937291e6735 to your computer and use it in GitHub Desktop.
timer.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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