MODULES¶
SmartTimer¶
-
class
smarttimers.smarttimer.
SmartTimer
(name='', **kwargs)[source]¶ Timer container to perform time measurements in code blocks.
Parameters: A
SmartTimer
allows recording elapsed time in an arbitrary number of code blocks. Specified points in the code are marked as either the beginning of a block to measure,tic()
, or as the end of a measured block,toc()
. Times are managed internally and ordered based ontic()
calls. Times can be queried, operated on, and written to file.- The following schemes are supported for timing code blocks
- Consecutive:
tic('A')
,toc()
, …,tic('B')
,toc()
- Cascade:
tic('A')
,toc()
,toc()
, … - Nested:
tic('A')
,tic('B')
, …,toc()
,toc()
- Label-paired:
tic('A')
,tic('B')
, …,toc('A')
,toc('B')
- Mixed: arbitrary combinations of schemes
- Consecutive:
-
name
¶ str – Name of container. May be used for filename in
write_to_file()
.
-
labels
¶ list, str – Label identifiers of completed timed code blocks.
-
active_labels
¶ list, str – Label identifiers of active code blocks.
-
seconds
¶ list, float – Elapsed time for completed code blocks.
-
minutes
¶ list, float – Elapsed time for completed code blocks.
-
times
¶ dict – Map of times elapsed for completed blocks. Keys are the labels used when invoking
tic()
.
-
__getitem__
(*keys)[source]¶ Query time(s) of completed code blocks.
Parameters: keys (str, slice, integer) – Key(s) to select times. If string, then consider it as a label used in tic()
. If integer or slice, then consider it as an index (based ontic()
ordering). Key types can be mixed.Returns: If key did not match a completed Timer label. list, float: Time in seconds of completed code blocks. Return type: None
-
tic
(label='')[source]¶ Start measuring time.
Measure time at the latest moment possible to minimize noise from internal operations.
Parameters: label (str) – Label identifier for current code block.
-
toc
(label=None)[source]¶ Stop measuring time at end of code block.
Note
In cascade regions, that is, multiple toc() calls, O(ms) noise will be introduced. In a future release, there is the possibility of correcting this noise, but even the correction is noise itself.
Parameters: label (str) – Label identifier for current code block. Returns: Measured time in seconds. Return type: float Raises: TimerError, KeyError – If there is not a matching tic()
.
-
walltime
()[source]¶ Compute elapsed time in seconds between first
tic()
and most recenttoc()
.walltime()
>= sum(seconds
)
-
remove
(*keys)[source]¶ Remove time(s) of completed code blocks.
Parameters: keys (str, slice, integer) – Key(s) to select times. If string, then consider it as a label used in tic()
. If integer or slice, then consider it as an index (based ontic()
ordering). Key types can be mixed.
-
dump_times
(filename=None, mode='w')[source]¶ Write timing results to a file.
If filename is provided, then it will be used as the filename. Otherwise
name
is used if non-empty, else the default filename is used. The extension .times is appended only if filename does not already has an extension. Using mode the file can be overwritten or appended with timing data.Parameters: - filename (str, optional) – Name of file.
- mode (str, optional) – Mode flag passed to open. Default is w.
-
stats
(label=None)[source]¶ Compute total, min, max, and average stats for timings.
Note
- An alphanumeric label is used as a word-bounded regular expression.
- A non-alphanumeric label is compared literally.
- If label is ‘None’ then all completed timings are used.
Parameters: label (str, iterable, optional) – String/regex used to match timer labels to select. Returns: Namespace with stats in seconds/minutes. Return type: types.SimpleNamespace
-
to_array
()[source]¶ Return timing data as a list or numpy array (no labels).
Data is arranged as a transposed view of
__str__()
andto_file()
formats.Returns: Timing data. Return type: numpy.ndarray, list
-
dump_profile
(filename=None, mode='w')[source]¶ Write profiling results to a file.
If filename is provided, then it will be used as the filename. Otherwise
name
is used if non-empty, else the default filename is used. The extension .prof is appended only if filename does not already has an extension. Using mode the file can be overwritten or appended with timing data.Parameters: - filename (str, optional) – Name of file.
- mode (str, optional) – Mode flag passed to open. Default is w.
Timer¶
-
class
smarttimers.timer.
Timer
(label='', **kwargs)[source]¶ Read current time from a clock/counter.
Parameters: - label (str, optional) – Label identifier. Default is empty string.
- kwargs (dict, optional) – Map of options. Valid options are
seconds
,clock_name
, andtimer
. - seconds (float, optional) – Time measured in fractional seconds. Default is 0.0.
- clock_name (str, optional) – Clock name used to select a time
measurement function. Default is
DEFAULT_CLOCK_NAME
. - timer (Timer, optional) – Reference instance to use as initialization.
A
Timer
allows recording the current time measured by a registered timing function. Time is recorded in fractional seconds and fractional minutes.Timer
supports addition, difference, and logical operators.Timer
uses a simple and extensible API which allows registering new timing functions. A timing function is compliant if it returns a time measured in fractional seconds. The function can contain arbitrary positional and/or keyword arguments or no arguments.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
from smarttimers import Timer # Find the current time function of a Timer t1 = Timer('Timer1') print(Timer.CLOCKS[t1.clock_name]) # or Timer.print_clocks() print(t1.clock_name) # Change current time function t1.clock_name = 'process_time' # Record a time measurement t1.time() print(t1) # Create another Timer compatible with 'Timer1' t2 = Timer('Timer2', clock_name='process_time') t2.print_info() t2.time() print(t2) # Sum Timers t3 = Timer.sum(t1, t2) # or t3 = t1 + t2 print(t3) # Find difference between Timers t4 = Timer.diff(t1, t2) # or t4 = t2 - t1 print(t4) # Compare Timers print(t1 == t2) # False print(t2 > t1) # True print(t4 <= t3) # True
- Available time measurement functions in
CLOCKS
: - ‘perf_counter’ -> time.perf_counter()
- ‘process_time’ -> time.process_time()
- ‘clock’ -> time.clock() (deprecated)
- ‘monotonic’ -> time.monotonic()
- ‘time’ -> time.time() (deprecated)
def custom_time_function(*args, **kwargs): # Measure time time_in_some_unit = ... # Convert time to fractional seconds time_seconds = time_in_some_unit ... return time_seconds # Register custom_time_function() as 'custom_time' Timer.register_clock('custom_time', custom_time_function) # or Timer.CLOCKS['custom_time'] = custom_time_function
Note
- New timing functions need to have a compliant interface. If a user wants to register a non-compliant timing function, a compliant wrapper function can be used. The available timing functions are built-ins from the standard time library.
- Only Timers with compatible clocks support arithmetic and logical
operators. Otherwise a
TimerCompatibilityError
exception occurs.
-
DEFAULT_CLOCK_NAME
¶ str – Default clock name, used when
clock_name
is empty string.Raises: TypeError
– If not a string.
-
CLOCKS
¶ TimerDict
, str -> callable – Map between clock name and time measurement functions.Raises: TypeError
– If not assigned with dictionary.KeyError
– If key is not a string.ValueError
– If assigned item is not callable.
-
label
¶ str – Label identifier.
Raises: TypeError
– If not a string.
-
seconds
¶ float, read-only – Time measured in fractional seconds.
Set internally either during initialization or when recording time.
Raises: TypeError
– If not numeric.ValueError
– If negative number.
-
minutes
¶ float, read-only – Time measured in minutes.
-
clock_name
¶ str – Clock name used to select a time measurement function.
Indexes the
CLOCKS
map to select a time function. If set to the empty string thenDEFAULT_CLOCK_NAME
is used. An instance is reset when set to a new and incompatible clock name.Raises: TypeError
– If not a string.
-
time
(*args, **kwargs)[source]¶ Record time using timing function configured via
clock_name
.Parameters: - args (tuple, optional) – Positional arguments for time function.
- kwargs (dict, optional) – Keyword arguments for time function.
Returns: Time measured in fractional seconds.
Return type: float
-
get_info
()[source]¶ Return clock information.
Returns: Namespace with clock info. Return type: types.SimpleNamespace
-
is_compatible
(timer)[source]¶ Return truth of compatibility between a
Timer
pair.For a
clock_name
that can be queried with time.get_clock_info, compatibility requires that all attributes are identical. Otherwise the timing functions have to be the same.Parameters: timer (Timer) – Second instance. Returns: True if compatible, else False. Return type: bool
-
classmethod
register_clock
(clock_name, clock_func)[source]¶ Registers a time function to
CLOCKS
map.Parameters: - clock_name (str) – Clock name.
- clock_func (callable) – Reference to a time measurement function.
Decorators¶
SmartTimer decorators
- Functions:
time()
-
smarttimers.decorators.
time
(func=None, *, timer=None)[source]¶ Measure runtime for functions/methods.
Parameters: timer (SmartTimer, optional) – Instance to use to measure time. If None, then global SmartTimer instance, _timer, is used.