sciris.sc_datetime.timer

class timer(label=None, auto=False, start=True, **kwargs)[source]

Bases: prettyobj

Simple timer class. Note: sc.timer() and sc.Timer() are aliases.

This wraps tic and toc with the formatting arguments and the start time (at construction).

Use this in a with block to automatically print elapsed time when the block finishes.

Parameters
  • label (str) – label identifying this timer

  • auto (bool) – whether to automatically increment the label

  • start (bool) – whether to start timing from object creation (else, call timer.tic() explicitly)

  • kwargs (dict) – passed to toc() when invoked

Example making repeated calls to the same timer, using auto to keep track:

>>> T = sc.timer(auto=True)
>>> T.toc()
(0): 2.63 s
>>> T.toc()
(1): 5.00 s

Example wrapping code using with-as:

>>> with sc.timer('mylabel'):
>>>     sc.timedsleep(0.5)

Example using a timer to collect data, using tt() as an alias for toctic() to reset the time:

T = sc.timer(doprint=False)
for key in 'abcde':
    sc.timedsleep(pl.rand())
    T.tt(key)
print(T.timings)

Implementation based on https://preshing.com/20110924/timing-your-code-using-pythons-with-statement/

New in version 1.3.0: sc.timer() alias, and allowing the label as first argument.
New in version 1.3.2: toc() passes label correctly; tt() method; auto argument
New in version 2.0.0: plot() method; total() method; indivtimings and cumtimings properties

Attributes

cumtimings

indivtimings

Methods

plot

Create a plot of Timer.timings

start

Alias for tic()

stop

Alias for toc()

tic

Set start time

toc

Print elapsed time; see sc.toc() for keyword arguments

tocout

Alias for toc() with output=True

toctic

Like toc, but reset time between timings

total

Calculate total time

tt

Alias for toctic()

tto

Alias for toctic() with output=True

tic()[source]

Set start time

toc(label=None, **kwargs)[source]

Print elapsed time; see sc.toc() for keyword arguments

total()[source]

Calculate total time

start()[source]

Alias for tic()

stop(*args, **kwargs)[source]

Alias for toc()

tocout(label=None, output=True, **kwargs)[source]

Alias for toc() with output=True

toctic(*args, reset=True, **kwargs)[source]

Like toc, but reset time between timings

tt(*args, **kwargs)[source]

Alias for toctic()

tto(*args, output=True, **kwargs)[source]

Alias for toctic() with output=True

plot(fig=None, figkwargs=None, grid=True, **kwargs)[source]

Create a plot of Timer.timings

Parameters
  • cumulative (bool) – how the timings will be presented, individual or cumulative

  • fig (fig) – an existing figure to draw the plot in

  • figkwargs (dict) – passed to pl.figure()

  • grid (bool) – whether to show a grid

  • kwargs (dict) – passed to pl.bar()

New in version 2.0.0.