TimedBlock#
- class TimedBlock(message: str = 'Running code block', timelimit: int = None)[source]#
Context manager for timing a block of code and reporting the timing.
- Parameters:
- messagestr
Message to log / print.
- timelimitint
Number of seconds to wait before raising an error. Floats are rounded down to an integer.
Warning
This context manager may only function on Linux/Unix machines (Windows is not currently supported).
Examples
>>> import time >>> import opinf
Without a time limit.
>>> with opinf.utils.TimedBlock(): ... # Code to be timed ... time.sleep(2) Running code block...done in 2.00 s.
With a custom message.
>>> with opinf.utils.TimedBlock("This is a test"): ... time.sleep(3) This is a test...done in 3.00 s.
With a time limit.
>>> with opinf.utils.TimedBlock("Another test", timelimit=3): ... # Code to be timed and halted within the specified time limit. ... i = 0 ... while True: ... i += 1 Another test... TimeoutError: TIMED OUT after 3.00s.
Set up a logfile to record messages to.
>>> opinf.utils.TimedBlock.setup_logfile("log.log") Logging to '/path/to/current/folder/log.log'
TimedBlock()
will now write to the log file as well as print to screen.>>> with opinf.utils.TimedBlock("logfile test"): ... time.sleep(1) logfile test...done in 1.00 s. >>> with open("log.log", "r") as infile: ... print(infile.read().strip()) INFO: logfile test...done in 1.001150 s.
Turn off print statements (but keep logging).
>>> opinf.utils.TimedBlock.verbose = False >>> with opinf.utils.TimedBlock("not printed to the screen"): ... time.sleep(1) >>> with open("log.log", "r") as infile: ... print(infile.read().strip()) INFO: logfile test...done in 1.001150 s. INFO: not printed to the screen...done in 1.002232 s.
Capture the time elapsed for later use.
>>> with opinf.utils.TimedBlock("how long?") as timer: ... time.sleep(2) >>> timer.elapsed 2.002866268157959
Properties:- elapsed#
Actual time (in seconds) the block took to complete.
- formatter = <logging.Formatter object>#
- rebuffer = False#
- timelimit#
Time limit (in seconds) for the block to complete.
- verbose = True#
Methods:Instruct
TimedBlock
to log messages to thelogfile
.