66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
This program has been developed by students from the bachelor Computer Science at Utrecht
|
|
University within the Software Project course.
|
|
© Copyright Utrecht University (Department of Information and Computing Sciences)
|
|
"""
|
|
|
|
import time
|
|
|
|
|
|
class TimeBlock(object):
|
|
"""
|
|
A context manager that times the execution of the block it contains. If execution exceeds the
|
|
limit, or if no limit is given, the callback will be called with the time that the block took.
|
|
|
|
:param callback: The callback function that is called when the block of code is over,
|
|
unless the code block did not exceed the time limit.
|
|
:type callback: Callable[[float], None]
|
|
|
|
:param limit_ms: The number of milliseconds the block of code is allowed to take. If it
|
|
exceeds this time, or if it's None, the callback function will be called with the time the
|
|
block took.
|
|
:type limit_ms: int | None
|
|
|
|
:ivar limit_ms: The number of milliseconds the block of code is allowed to take.
|
|
:vartype limit_ms: float | None
|
|
|
|
:ivar callback: The callback function that is called when the block of code is over.
|
|
:vartype callback: Callable[[float], None]
|
|
|
|
ivar start: The start time of the block, set when entering the context.
|
|
:vartype start: float | None
|
|
"""
|
|
def __init__(self, callback, limit_ms=None):
|
|
self.limit_ms = float(limit_ms) if limit_ms is not None else None
|
|
self.callback = callback
|
|
self.start = None
|
|
|
|
def __enter__(self):
|
|
"""
|
|
Enter the context manager and record the start time.
|
|
|
|
:return: Returns itself so timing information can be accessed if needed.
|
|
:rtype: TimeBlock
|
|
"""
|
|
self.start = time.time()
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
"""
|
|
Exit the context manager, calculate the elapsed time, and call the callback
|
|
if the time limit was exceeded or not provided.
|
|
|
|
:param exc_type: The exception type, or None if no exception occurred.
|
|
:type exc_type: Type[BaseException] | None
|
|
|
|
:param exc_value: The exception instance, or None if no exception occurred.
|
|
:type exc_value: BaseException | None
|
|
|
|
:param traceback: The traceback object, or None if no exception occurred.
|
|
:type traceback: TracebackType | None
|
|
"""
|
|
elapsed = (time.time() - self.start) * 1000.0 # ms
|
|
if self.limit_ms is None or elapsed > self.limit_ms:
|
|
self.callback(elapsed)
|