Skip to content

Commit

Permalink
update timer to allow access to runtime dynamically (previously, the …
Browse files Browse the repository at this point in the history
…context manager would garbage-collect before you could access it)
  • Loading branch information
peterdsharpe committed Mar 11, 2024
1 parent 5dcdf41 commit 31dff8d
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions aerosandbox/tools/code_benchmarking.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,20 @@ class Timer(object):
with Timer("My timer"): # You can optionally give it a name
# Do stuff
Results are printed to stdout. You can access the runtime (in seconds) directly with:
Results are printed to stdout. You can access the runtime (in seconds) directly by instantiating the object:
>>> with Timer("My timer") as t:
>>> # Do stuff
>>> print(t.runtime) # You can dynamically access the runtime of any completed Timer, if desired
>>> t = Timer("My timer")
>>> t.tic()
>>> # Do stuff
>>> print(t.toc())
Nested timers are also supported. For example, this code:
>>> with Timer("a"):
>>> with Timer("b"):
>>> with Timer("c"):
>>> f()
yields the following console output:
prints the following console output:
[a] Timing...
[b] Timing...
Expand Down Expand Up @@ -69,19 +70,26 @@ def _print(self, s: str, number_running_mod: int = 0):
header += f"[{self.name}] "
print(header + s)

def __enter__(self):
def tic(self):
self.__class__.number_running += 1
self._print("Timing...")
self.t_start = time.perf_counter_ns()

def __exit__(self, type, value, traceback):
def __enter__(self):
self.tic()

def toc(self) -> float:
self.t_end = time.perf_counter_ns()
self.__class__.number_running -= 1
self.runtime = (self.t_end - self.t_start) / 1e9
self._print(
f"Elapsed: {self._format_time(self.runtime)}",
number_running_mod=1
)
return self.runtime

def __exit__(self, type, value, traceback):
self.toc()


def time_function(
Expand Down Expand Up @@ -164,3 +172,8 @@ def f():
with Timer("b") as b:
with Timer("c") as c:
f()

t = Timer()
t.tic()
time.sleep(0.1)
print(t.toc())

0 comments on commit 31dff8d

Please sign in to comment.