Skip to content

Instantly share code, notes, and snippets.

@reimaruyama
Last active June 28, 2020 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reimaruyama/ad0461e9a6219ffc98dad18cdde0d24d to your computer and use it in GitHub Desktop.
Save reimaruyama/ad0461e9a6219ffc98dad18cdde0d24d to your computer and use it in GitHub Desktop.
Python stop watch
from time import time
class StopWatch:
def __init__(self):
self.start_time = 0
self.stop_time = 0
self.total_time = 0
def __enter__(self) -> "StopWatch":
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> "StopWatch":
self.stop()
return self
def is_stopped(self) -> bool:
if self.total_time:
return True
return False
def elapsed_time(self) -> int:
if self.is_stopped():
return self.total_time
return time() - self.start_time
def start(self) -> None:
self.start_time = time()
def stop(self) -> None:
self.stop_time = time()
self.total_time = self.stop_time - self.start_time
# Sample use case
def main():
with StopWatch() as stop_watch:
print("processing...")
# main logic
# Check total time main logic took
print(stop_watch.elapsed_time())
with StopWatch() as stop_watch:
while True:
print("Hello.")
# You can check duration from inside 'with' block
if stop_watch.elapsed_time() > 3:
break
print(stop_watch.elapsed_time())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment