SNN2.src.contextManagers.contextManagers module
Context Managers Module
This module provides context managers and utilities for timing code execution and handling augmented class names within the SNN2 framework.
The module contains both function-based and class-based context managers that can be used to measure execution times of code blocks, with optional logging support. These tools are essential for performance monitoring and profiling in neural network training and data processing pipelines.
Functions
- get_realNamefunction
Extract the real name from objects, handling augmented classes.
- timeit_cntcontextmanager
Context manager for timing code execution with logging support.
Classes
- TimeitContextclass
Reusable context manager for collecting timing statistics across multiple runs.
Examples
Basic timing with logging:
>>> with timeit_cnt("data_processing"):
... # Some data processing code
... process_data()
data_processing execution time: 1234.567 ms
Reusable timing context:
>>> timer = TimeitContext()
>>> for i in range(3):
... with timer():
... time.sleep(0.1)
>>> print(f"Mean execution time: {timer.mean:.3f}s")
Mean execution time: 0.100s
Notes
This module integrates with the SNN2 logging system through the f_logger decorator, providing consistent logging behavior across the framework. All timing measurements are performed using Python’s time.time() function for high-resolution timing.
See also
SNN2.src.decorators.decoratorsDecorator functions including f_logger
SNN2.src.io.loggerLogging utilities and LogHandler class
- class SNN2.src.contextManagers.contextManagers.TimeitContext
Bases:
objectA reusable context manager for timing multiple code executions.
This class provides a context manager that can be reused multiple times to measure execution times and collect statistics about performance.
- all_times
List storing all recorded execution times in seconds.
- Type:
list of float
- execution_time
The most recent execution time in seconds.
- Type:
float or None
- n_runs
Number of times the context manager has been used.
- Type:
int
Examples
>>> timer = TimeitContext() >>> with timer(): ... time.sleep(0.1) >>> print(f"Execution time: {timer.execution_time:.3f}s") >>> print(f"Mean time: {timer.mean:.3f}s")
- property mean
Calculate the mean execution time across all runs.
- Returns:
The average execution time in seconds across all recorded runs.
- Return type:
float
- Raises:
ZeroDivisionError – If no runs have been recorded (all_times is empty).
Notes
This property computes the arithmetic mean of all execution times stored in the all_times list.
- SNN2.src.contextManagers.contextManagers.get_realName(obj: Any)
Get the real name of an object, handling augmented classes.
- Parameters:
obj (Any) – The object whose real name should be retrieved.
- Returns:
The real name of the object. If the object is an augmented class with a custom name, returns the passed name, otherwise returns the qualified name.
- Return type:
str
Notes
This function is designed to handle special cases where objects have been augmented and their original name has been stored in a c_passed_name attribute.
- SNN2.src.contextManagers.contextManagers.timeit_cnt(name, active: bool = True, *, logger=None, write_msg=<function f_logger.<locals>.__dummy_log>, **kwargs)
Context manager for timing code execution with logging support.
This context manager measures the execution time of a code block and optionally logs the result using the provided logger.
- Parameters:
name (str) – Name identifier for the timed operation, used in log messages.
*args (tuple) – Variable length argument list (not used in current implementation).
active (bool, default=True) – Whether to actively log and print timing results.
**kwargs (dict) – Keyword arguments containing logger and write_msg from f_logger decorator.
- Yields:
None – Control is yielded to the code block being timed.
Notes
This function is decorated with @f_logger which automatically provides logger and write_msg in kwargs. The timing results are both logged and printed to stdout when active=True.
Examples
>>> with timeit_cnt("my_operation"): ... # Some time-consuming operation ... time.sleep(1) my_operation execution time: 1000.123 ms