This documentation provides details on the TicToc
class, a simple utility for timing operations in Python applications.
The TicToc
class serves as a basic stopwatch, allowing users to measure the time elapsed between two points in their code. It is useful for performance testing, debugging, and timing any operation that requires precision.
The TicToc
class holds a static member begin_time
which stores the time when the timer was started.
class TicToc:
begin_time: datetime.datetime = None
Starts the timer by recording the current time. An optional boolean argument can be passed to print the start time.
def tic(b_print: bool = False):
TicToc.begin_time = datetime.datetime.now()
if b_print:
print(TicToc.begin_time)
Calculates the time elapsed since tic()
was called. It does not stop the timer but measures the elapsed time up to the point of invocation. It can either return this value as a float or print it, depending on the returns
flag.
def toc(returns: bool = False, decimals: int = 3) -> float | None:
if TicToc.begin_time is None:
return 0.0
t = datetime.datetime.now() - TicToc.begin_time
ct = t.total_seconds()
retval = numpy.round(ct, decimals)
if returns:
return retval
else:
print(f"{retval}")
To use the TicToc
class to measure the duration of a function:
from OPC_Connector.Helpers import TicToc
TicToc.tic() # Start timing
# Run your code here
duration = TicToc.toc(returns=True) # Get elapsed time
print(f"Elapsed time: {duration} seconds")
Note: Ensure that you call tic()
before toc()
to properly measure time.
For more details on Python's datetime
and numpy
libraries, refer to the official Python documentation. These libraries provide the necessary functions to handle precise timing and mathematical operations in TicToc
.