The Python signal
module provides an interface to set up and handle asynchronous events from the operating system, making it ideal for cases like implementing timeouts or benchmarking the performance of a function. By scheduling a signal to be sent after a certain interval, you can interrupt a long-running task if it exceeds an expected duration, or measure how many operations can be processed within a set time frame.
Below is a simple example that benchmarks how many times a function can run within a set time period using the signal module. In this example, the signal alarm is set to trigger after 5 seconds, interrupting a loop that repeatedly calls the target function and counting the number of iterations completed.
import signal
# Custom exception for timeout
class TimeoutException(Exception):
pass
# Signal handler that raises a timeout exception
def timeout_handler(signum, frame):
raise TimeoutException("Benchmark time elapsed!")
# Register the signal handler for SIGALRM
signal.signal(signal.SIGALRM, timeout_handler)
def function_to_benchmark():
# Example function: perform a simple calculation
return sum(range(10))
def benchmark_function(timeout_seconds=5):
count = 0
# Set an alarm for the benchmark duration
signal.alarm(timeout_seconds)
try:
while True:
function_to_benchmark()
count += 1
except TimeoutException:
pass
finally:
signal.alarm(0) # Cancel the alarm
return count
if __name__ == '__main__':
iterations = benchmark_function(5)
print(f"Function executed {iterations} times in 5 seconds.")
In this code, function_to_benchmark
represents the task being measured. The benchmark_function
repeatedly calls it until the 5-second alarm triggers the timeout_handler
, which raises a TimeoutException
to break out of the loop. The total number of iterations completed during that period is then printed.