Skip to content

Create timer_berkin_yildirim.py #742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Week06/timer_berkin_yildirim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import time
from typing import Optional, Callable

class Timer:
def __init__(self, log: bool = True, callback: Optional[Callable[[float], None]] = None):
"""
Initialize the Timer with optional logging and a callback function.
:param log: If True, logs start and end messages; if False, remains silent.
:param callback: An optional function to call with the elapsed time when exiting.
"""
self.log = log
self.callback = callback
self.start_time = None
self.end_time = None
self.elapsed_time = None
if self.log:
print(f"{self.__class__.__name__} initialized.")

def __enter__(self) -> "Timer":
"""
Start the timer upon entering the context.
"""
self.start_time = time.time()
if self.log:
print(f"{self.__class__.__name__} started.")
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
"""
Stop the timer upon exiting the context and calculate the elapsed time.
Calls the callback function if provided.
"""
self.end_time = time.time()
self.elapsed_time = self.end_time - self.start_time
if self.log:
print(f"{self.__class__.__name__} ended. Elapsed time: {self.elapsed_time:.4f} seconds")

# If a callback is provided, call it with the elapsed time
if self.callback:
self.callback(self.elapsed_time)

# Return False to allow any exceptions to propagate
return False
Loading