87. timer — A timer class.

class timer.Timer(start=None, tag=None)[source]

A class for measuring elapsed time.

A Timer object measures elapsed real time since a specified time, which by default is the time of the creation of the Timer. A builtin tag can be used for identifying subsequent measurements.

Parameters:

  • start: a datetime object. If not specified, the time of the creation of the Timer is used.
  • tag: a string used as an identifier for the current measurement. It is displayed when printing the Timer value

Example:

>>> import time
>>> t = Timer()
>>> time.sleep(1.234)
>>> r = t.read()
>>> print(r.days, r.seconds, r.microseconds)  # doctest: +ELLIPSIS
0 1 23...
>>> t.seconds()  # doctest: +ELLIPSIS
1.23...
>>> t.seconds(rounded=True)
1

Note that the precise result of microseconds will be slightly larger than the input sleep time. The precise result is unknown, therefore ellipses are shown.

>>> tim = Timer(tag="First")
>>> time.sleep(0.13)
>>> print(tim)
Timer: First: 0.13 sec.
>>> tim.reset(tag="Next")
>>> time.sleep(0.13)
>>> print(tim)
Timer: Next: 0.13 sec.
reset(start=None, tag=None)[source]

(Re)Start the timer.

Sets the start time of the timer to the specified value, or to the current time if not specified. Sets the tag to the specified value or to ‘None’.

Parameters:

  • start: a datetime object. If not specified, the current time as returned by datetime.now() is used.
  • tag: a string used as an identifier for the current measurement
read(reset=False)[source]

Read the timer.

Returns the elapsed time since the last reset (or the creation of the timer) as a datetime.timedelta object.

If reset=True, the timer is reset to the time of reading.

seconds(reset=False, rounded=False)[source]

Return the timer readings in seconds.

The default return value is a rounded integer number of seconds. With rounded == False, a floating point value with granularity of 1 microsecond is returned.

If reset=True, the timer is reset at the time of reading.

report(format='%.2f sec.')[source]

Report the elapsed time in seconds since last reset