Skip to content
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

Adding tick based triggers, minimum elasped time triggers and total t… #54

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
21 changes: 20 additions & 1 deletion codetiming/_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,13 @@ class Timer(ContextDecorator):
timers: ClassVar[Timers] = Timers()
name: Optional[str] = None
text: Union[str, FloatArg, Callable[[float], str]] = "Elapsed time: {:0.4f} seconds"
totaltext: Union[str, FloatArg, Callable[[float], str]] = "Total time: {:0.4f} seconds"
initial_text: Union[bool, str, FloatArg] = False
logger: Optional[Callable[[str], None]] = print
last: float = field(default=math.nan, init=False, repr=False)
tick: int = field(default=0, init=False, repr=False)
period: int = field(default=100, init=False, repr=False)
min : Optional[int] = 0
_start_time: Optional[float] = field(default=None, init=False, repr=False)

def start(self) -> None:
Expand All @@ -74,11 +78,12 @@ def stop(self) -> float:
raise TimerError("Timer is not running. Use .start() to start it")

# Calculate elapsed time
self.tick += 1
self.last = time.perf_counter() - self._start_time
self._start_time = None

# Report elapsed time
if self.logger:
if self.logger and ((self.last >= self.min)) :
if callable(self.text):
text = self.text(self.last)
else:
Expand All @@ -87,11 +92,25 @@ def stop(self) -> float:
"milliseconds": self.last * 1000,
"seconds": self.last,
"minutes": self.last / 60,
"tick": self.tick
}
text = self.text.format(self.last, **attributes)
self.logger(str(text))
if self.name:
self.timers.add(self.name, self.last)
if (self.tick % self.period) == 0:
if callable(self.totaltext):
text = self.totaltext(self.timers.total(self.name))
else:
attributes = {
"name": self.name,
"milliseconds": self.last * 1000,
"seconds": self.last,
"minutes": self.last / 60,
"tick": self.tick
}
text = self.totaltext.format(self.timers.total(self.name), **attributes)
self.logger(str(text))

return self.last

Expand Down