8. Function Reference

gtimer.start(backdate=None)

Mark the start of timing, overwriting the automatic start data written on import, or the automatic start at the beginning of a subdivision.

Notes

Backdating: For subdivisions only. Backdate time must be in the past but more recent than the latest stamp in the parent timer.

Parameters:

backdate (float, optional) – time to use for start instead of current.

Returns:

float – The current time.

Raises:
  • BackdateError – If given backdate time is out of range or used in root timer.
  • StartError – If the timer is not in a pristine state (if any stamps or subdivisions, must reset instead).
  • StoppedError – If the timer is already stopped (must reset instead).
  • TypeError – If given backdate value is not type float.
gtimer.stamp(name, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None)

Mark the end of a timing interval.

Notes

If keeping subdivisions, each subdivision currently awaiting assignment to a stamp (i.e. ended since the last stamp in this level) will be assigned to this one. Otherwise, all awaiting ones will be discarded after aggregating their self times into the current timer.

If both long- and short-form are present, they are OR’ed together. If neither are present, the current global default is used.

Backdating: record a stamp as if it happened at an earlier time. Backdate time must be in the past but more recent than the latest stamp. (This can be useful for parallel applications, wherein a sub- process can return times of interest to the master process.)

Warning

When backdating, awaiting subdivisions will be assigned as normal, with no additional checks for validity.

Parameters:
  • name (any) – The identifier for this interval, processed through str()
  • backdate (float, optional) – time to use for stamp instead of current
  • unique (bool, optional) – enforce uniqueness
  • keep_subdivisions (bool, optional) – keep awaiting subdivisions
  • quick_print (bool, optional) – print elapsed interval time
  • un (bool, optional) – short-form for unique
  • ks (bool, optional) – short-form for keep_subdivisions
  • qp (bool, optional) – short-form for quick_print
Returns:

float – The current time.

Raises:
  • BackdateError – If the given backdate time is out of range.
  • PausedError – If the timer is paused.
  • StoppedError – If the timer is stopped.
  • TypeError – If the given backdate value is not type float.
gtimer.stop(name=None, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None)

Mark the end of timing. Optionally performs a stamp, hence accepts the same arguments.

Notes

If keeping subdivisions and not calling a stamp, any awaiting subdivisions will be assigned to a special ‘UNASSIGNED’ position to indicate that they are not properly accounted for in the hierarchy (these can happen at different places and may be combined inadvertently).

Backdating: For subdivisions only. Backdate time must be in the past but more recent than the latest stamp.

Parameters:
  • name (any, optional) – If used, passed to a call to stamp()
  • backdate (float, optional) – time to use for stop instead of current
  • unique (bool, optional) – see stamp()
  • keep_subdivisions (bool, optional) – keep awaiting subdivisions
  • quick_print (bool, optional) – boolean, print total time
  • un (bool, optional) – see stamp()
  • ks (bool, optional) – see stamp()
  • qp (bool, optional) – see stamp()
Returns:

float – The current time.

Raises:
  • BackdateError – If given backdate is out of range, or if used in root timer.
  • PausedError – If attempting stamp in paused timer.
  • StoppedError – If timer already stopped.
  • TypeError – If given backdate value is not type float.
gtimer.pause()

Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands.

Returns:

float – The current time.

Raises:
  • PausedError – If timer already paused.
  • StoppedError – If timer already stopped.
gtimer.resume()

Resume a paused timer, re-activating it. Subsequent time accumulates in the total.

Returns:

float – The current time.

Raises:
  • PausedError – If timer was not in paused state.
  • StoppedError – If timer was already stopped.
gtimer.blank_stamp(name=None, backdate=None, unique=None, keep_subdivisions=False, quick_print=None, un=None, ks=False, qp=None)

Mark the beginning of a new interval, but the elapsed time of the previous interval is discarded. Intentionally the same signature as stamp().

Notes

The default for keep_subdivisions is False (does not refer to an adjustable global setting), meaning that any subdivisons awaiting would be discarded after having their self times aggregated into this timer. If this is set to True, subdivisions are put in the ‘UNASSIGNED’ position, indicating they are not properly accounted for in the hierarchy.

Parameters:
  • name (any, optional) – Inactive.
  • backdate (any, optional) – Inactive.
  • unique (any, optional) – Inactive.
  • keep_subdivisions (bool, optional) – Keep subdivisions awaiting
  • quick_print (any, optional) – Inactive.
  • un (any, optional) – Inactive.
  • ks (bool, optional) – see stamp().
  • qp (any, optional) – Inactive.
Returns:

float – The current time.

Raises:

StoppedError – If timer is already stopped.

gtimer.reset()

Reset the timer at the current level in the hierarchy (i.e. might or might not be the root).

Notes

Erases timing data but preserves relationship to the hierarchy. If the current timer level was not previously stopped, any timing data from this timer (including subdivisions) will be discarded and not added to the next higher level in the data structure. If the current timer was previously stopped, then its data has already been pushed into the next higher level.

Returns:float – The current time.
Raises:LoopError – If in a timed loop.
gtimer.current_time()

Returns the current time using timeit.default_timer() (same as used throughout gtimer).

Returns:float – the current time
gtimer.subdivide(name, rgstr_stamps=None, save_itrs=True)

Induce a new subdivision–a lower level in the timing hierarchy. Subsequent calls to methods like stamp() operate on this new level.

Notes

If rgstr_stamps is used, the collection is passed through set() for uniqueness, and the each entry is passed through str(). Any identifiers contained within are guaranteed to exist in the final dictionaries of stamp data when this timer closes. If any registered stamp was not actually encountered, zero values are populated. (Can be useful if a subdivision is called repeatedly with conditional stamps.)

The save_itrs input defaults to the current global default. If save_itrs is True, then whenever another subdivision by the same name is added to the same position in the parent timer, and the two data structures are merged, any stamps present only as individual stamps (but not as itrs) will be made into itrs, with each subsequent data dump (when a subdivision is stopped) treated as another iteration. (Consider multiple calls to a timer-wrapped subfunction within a loop.) This setting does not affect any other timers in the hierarchy.

Parameters:
  • name (any) – Identifer for the new timer, passed through str().
  • rgstr_stamps (list,tuple, optional) – Identifiers.
  • save_itrs (bool, optional) – Save individual iteration data.
Returns:

None

gtimer.end_subdivision()

End a user-induced timing subdivision, returning the previous level in the timing hierarchy as the target of timing commands such as stamp(). Includes a call to stop(); a previous call to stop() is OK.

Returns:

None

Raises:
  • GTimerError – If current subdivision was not induced by user.
  • LoopError – If current timer is in a timed loop.
gtimer.timed_loop(name=None, rgstr_stamps=None, save_itrs=True, loop_end_stamp=None, end_stamp_unique=True, keep_prev_subdivisions=True, keep_end_subdivisions=True, quick_print=False)

Instantiate a TimedLoop object for measuring loop iteration timing data. Can be used with either for or while loops.

Example:

loop = timed_loop()
while x > 0:  # or for x in <iterable>:
    next(loop)  # or loop.next()
    <body of loop, with gtimer stamps>
loop.exit()

Notes

Can be used as a context manager around the loop, without requiring separate call to exit(). Redundant calls to exit() do no harm. Loop functionality is implemented in the next() or __next__() methods.

Each instance can only be used once, so for an inner loop, this function must be called within the outer loop.

Any awaiting subdivisions kept at entrance to a loop section will go to the ‘UNASSIGNED’ position to indicate that they are not properly accounted for in the hierarchy. Likewise for any awaiting subdivisions kept at the end of loop iterations without a named stamp.

Parameters:
  • name (any, optional) – Identifier (makes the loop a subdivision), passed through str().
  • rgstr_stamps (list, tuple, optional) – Identifiers, see subdivision().
  • save_itrs (bool, optional) – see subdivision().
  • loop_end_stamp (any, optional) – Identifier, automatic stamp at end of every iteration.
  • end_stamp_unique (bool, optional) – see stamp().
  • keep_prev_subdivisions (bool, optional) – Keep awaiting subdivisions on entering loop.
  • keep_end_subdivisions (bool, optional) – Keep awaiting subdivisions at end of iterations.
  • quick_print (bool, optional) – Named loop only, print at end of each iteration.
Returns:

TimedLoop – Custom gtimer object for measuring loops.

gtimer.timed_for(iterable, name=None, rgstr_stamps=None, save_itrs=True, loop_end_stamp=None, end_stamp_unique=True, keep_prev_subdivisions=True, keep_end_subdivisions=True, quick_print=False)

Instantiate a TimedLoop object for measuring for loop iteration timing data. Can be used only on for loops.

Example:

for i in gtimer.timed_for(iterable, ..):
    <body of loop with gtimer stamps>

Notes

Can be used as a context manager around the loop. When breaking out of the loop, requires usage either as a context manager or with a reference to the object on which to call the exit() method after leaving the loop body. Redundant calls to exit() do no harm. Loop functionality is implemented in the __iter__() method.

Each instance can only be used once, so for an inner loop, this function must be called within the outer loop.

Any awaiting subdivisions kept at entrance to a loop section will go to the ‘UNASSIGNED’ position to indicate that they are not properly accounted for in the hierarchy. Likewise for any awaiting subdivisions kept at the end of loop iterations without a named stamp.

Parameters:
  • iterable – Same as provided to regular ‘for’ command.
  • name (any, optional) – Identifier (makes the loop a subdivision), passed through str().
  • rgstr_stamps (list,tuple, optional) – Identifiers, see subdivision().
  • save_itrs (bool, optional) – see subdivision().
  • loop_end_stamp (any, optional) – Identifier, automatic stamp at end of every iteration, passed through str().
  • end_stamp_unique (bool, optional) – see stamp().
  • keep_prev_subdivisions (bool, optional) – Keep awaiting subdivisions on entering loop.
  • keep_end_subdivisions (bool, optional) – Keep awaiting subdivisions at end of iterations.
  • quick_print (bool, optional) – Named loop only, print at end of each iteration.
Returns:

TimedFor – Custom gtimer object for measuring for loops.

gtimer.reset_root()

Re-instantiate the entire underlying timer data structure and restart (same as first import), discarding all previous state and data.

Warning

This is a hard reset without hazard checks–always executes when called, any time, anywhere.

Returns:None
gtimer.rename_root(name)

Rename the root timer (regardless of current timing level).

Parameters:name (any) – Identifier, passed through str()
Returns:str – Implemented identifier.
gtimer.set_save_itrs_root(setting)

Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()).

Parameters:setting (bool) – Save individual iterations data, passed through bool()
Returns:bool – Implemented setting value.
gtimer.rgstr_stamps_root(rgstr_stamps)

Register stamps with the root timer (see subdivision()).

Parameters:rgstr_stamps (list, tuple) – Collection of identifiers, passed through set(), then each is passed through str().
Returns:list – Implemented registered stamp collection.
gtimer.set_def_save_itrs(setting)

Set the global default (henceforth) behavior whether to save individual iteration data of new subdivisions and loops.

Parameters:setting – Passed through bool().
Returns:bool – Implemented setting value.
gtimer.set_def_keep_subdivisions(setting)

Set the global default (henceforth) behavior whether to keep awaiting subdivisions when stamping.

Parameters:setting – Passed through bool().
Returns:bool – Implemented setting value.
gtimer.set_def_quick_print(setting)

Set the global default (henceforth) behavior whether to quick print when stamping or stopping.

Parameters:setting – Passed through bool().
Returns:bool – Implemented setting value.
gtimer.set_def_unique(setting)

Set the global default (henceforth) behavior whether to enforce unique stamp names (recommended).

Parameters:setting – Passed through bool().
Returns:bool – Implemented setting value.
gtimer.get_times()

Produce a deepcopy of the current timing data (no risk of interference with active timing or other operaitons).

Returns:Times – gtimer timing data structure object.
gtimer.save_pkl(filename=None, times=None)

Serialize and / or save a Times data object using pickle (cPickle).

Parameters:
  • filename (None, optional) – Filename to dump to. If not provided, returns serialized object.
  • times (None, optional) – object to dump. If non provided, uses current root.
Returns:

pkl – Pickled Times data object, only if no filename provided.

Raises:

TypeError – If ‘times’ is not a Times object or a list of tuple of them.

gtimer.load_pkl(filenames)

Unpickle file contents.

Parameters:filenames (str) – Can be one or a list or tuple of filenames to retrieve.
Returns:Times – A single object, or from a collection of filenames, a list of Times objects.
Raises:TypeError – If any loaded object is not a Times object.
gtimer.attach_par_subdivision(par_name, par_times)

Manual assignment of a collection of (stopped) Times objects as a parallel subdivision of a running timer.

Notes

An example sequence of proper usage:

  1. Stamp in master process.
  2. Run timed sub-processes.
  3. Get timing data from sub-processes into master.
  4. Attach timing data (i.e. list of Times objects) in master using this method.
  5. Stamp in master process.

To stamp in the master between steps 1 and 5, it is recommended to subdivide() between steps 1 and 2, and end that subdivision before attaching, or else the master stamp will not reflect the sub-process time.

Parameters:
  • par_name (any) – Identifier for the collection, passed through str()
  • par_times (list or tuple) – Collection of Times data objects.
Raises:

TypeError – If par_times not a list or tuple of Times data objects.

gtimer.attach_subdivision(times)

Manual assignment of a (stopped) times object as a subdivision of running timer. Use cases are expected to be very limited (mainly provided as a one-Times variant of attach_par_subdivision).

Notes

As with any subdivision, the interval in the receiving timer is assumed to totally subsume the time accumulated within the attached object–the total in the receiver is not adjusted!

Parameters:times (Times) – Individual Times data object.
Raises:TypeError – If times not a Times data object.
gtimer.report(times=None, include_itrs=True, include_stats=True, delim_mode=False, format_options=None)

Produce a formatted report of the current timing data.

Notes

When reporting a collection of parallel subdivisions, only the one with the greatest total time is reported on, and the rest are ignored (no branching). To compare parallel subdivisions use compare().

Parameters:
  • times (Times, optional) – Times object to report on. If not provided, uses current root timer.
  • include_itrs (bool, optional) – Display invidual iteration times.
  • include_stats (bool, optional) – Display iteration statistics.
  • delim_mode (bool, optional) – If True, format for spreadsheet.
  • format_options (dict, optional) – Formatting options, see below.
Formatting Keywords & Defaults:
Human-Readable Mode
  • ‘stamp_name_width’: 20
  • ‘itr_tab_width’: 2
  • ‘itr_num_width’: 6
  • ‘itr_name_width’: 12
  • ‘indent_symbol’: ‘ ‘ (two spaces)
  • ‘parallel_symbol’: ‘(par)’
Delimited Mode
  • ‘delimiter’: ‘ ‘ (tab)
  • ‘ident_symbol’: ‘+’
  • ‘parallel_symbol’: ‘(par)’
Returns:str – Timing data report as formatted string.
Raises:TypeError – If ‘times’ param is used and value is not a Times object.
gtimer.compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None)

Produce a formatted comparison of timing datas.

Notes

If no times_list is provided, produces comparison reports on all parallel subdivisions present at the root level of the current timer. To compare parallel subdivisions at a lower level, get the times data, navigate within it to the parallel list of interest, and provide that as input here. As with report(), any further parallel subdivisions encountered have only their member with the greatest total time reported on (no branching).

Parameters:
  • times_list (Times, optional) – list or tuple of Times objects. If not provided, uses current root timer.
  • name (any, optional) – Identifier, passed through str().
  • include_list (bool, optional) – Display stamps hierarchy.
  • include_stats (bool, optional) – Display stamp comparison statistics.
  • delim_mode (bool, optional) – If True, format for spreadsheet.
  • format_options (None, optional) – Formatting options, see below.
Formatting Keywords & Defaults:
Human-readable Mode
  • ‘stamp_name_width’: 18
  • ‘list_column_width’: 12
  • ‘list_tab_width’: 2
  • ‘stat_column_width’: 8
  • ‘stat_tab_width’: 2
  • ‘indent_symbol: ‘ ‘ (one space)
Delimited Mode
  • ‘delimiter’: ‘ ‘ (tab)
  • ‘ident_symbol’: ‘+’
Returns:str – Times data comparison as formatted string.
Raises:TypeError – If any element of provided collection is not a Times object.
gtimer.write_structure(times=None)

Produce a formatted record of a times data structure.

Parameters:times (Times, optional) – If not provided, uses the current root timer.
Returns:str – Timer tree hierarchy in a formatted string.
Raises:TypeError – If provided argument is not a Times object.