Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[Samples] throughput_benchmark.py - add arguments and signal handling (#38050)

Jakub Kwiatkowskicae33e7271d2
diff --git a/docs/articles_en/get-started/learn-openvino/openvino-samples/throughput-benchmark.rst b/docs/articles_en/get-started/learn-openvino/openvino-samples/throughput-benchmark.rst
index 892dd309bfd..b59fc29cc37 100644
--- a/docs/articles_en/get-started/learn-openvino/openvino-samples/throughput-benchmark.rst
+++ b/docs/articles_en/get-started/learn-openvino/openvino-samples/throughput-benchmark.rst
@@ -7,9 +7,9 @@ Throughput Benchmark Sample
This sample demonstrates how to estimate performance of a model using Asynchronous
-Inference Request API in throughput mode. This sample
-does not have other configurable command-line arguments. Feel free to modify sample's
-source code to try out different options.
+Inference Request API in throughput mode. The Python sample provides options for
+the benchmark duration, iteration count, can run continuously until
+a stop signal is received.
The reported results may deviate from what :doc:`benchmark_app <benchmark-tool>`
reports. One example is model input precision for computer vision tasks. benchmark_app
@@ -26,8 +26,9 @@ How It Works
####################
The sample compiles a model for a given device, randomly generates input data,
-performs asynchronous inference multiple times for a given number of seconds.
-Then, it processes and reports performance results.
+and performs asynchronous inference repeatedly. After the benchmark finishes, it
+waits for in-flight requests and reports performance results. The Python sample
+can use a finite duration or run continuously until a stop signal is received.
.. tab-set::
@@ -62,7 +63,7 @@ Running
.. code-block:: console
- python throughput_benchmark.py <path_to_model> <device_name>(default: CPU)
+ python throughput_benchmark.py <path_to_model> <device_name>(default: CPU) [--seconds-to-run SECONDS] [--niter NITER]
.. tab-item:: C++
diff --git a/samples/python/benchmark/throughput_benchmark/README.md b/samples/python/benchmark/throughput_benchmark/README.md
index a3e4a06272c..952f32023e7 100644
--- a/samples/python/benchmark/throughput_benchmark/README.md
+++ b/samples/python/benchmark/throughput_benchmark/README.md
@@ -1,11 +1,38 @@
# Throughput Benchmark Python Sample
-This sample demonstrates how to estimate performance of a model using Asynchronous Inference Request API in throughput mode. Unlike [demos](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos) this sample doesn't have other configurable command line arguments. Feel free to modify sample's source code to try out different options.
+This sample demonstrates how to estimate performance of a model using Asynchronous Inference Request API in throughput mode. You can configure the benchmark duration and minimum iteration count, or run continuously until a stop signal is received.
The reported results may deviate from what [benchmark_app](https://docs.openvino.ai/2026/get-started/learn-openvino/openvino-samples/benchmark-tool.html) reports. One example is model input precision for computer vision tasks. benchmark_app sets uint8, while the sample uses default model precision which is usually float32.
For more detailed information on how this sample works, check the dedicated [article](https://docs.openvino.ai/2026/get-started/learn-openvino/openvino-samples/sync-benchmark.html)
+## Usage
+
+```sh
+python throughput_benchmark.py <path_to_model> [device_name] [--seconds-to-run SECONDS] [--niter NITER]
+```
+
+The model path is required. The device defaults to `CPU`.
+
+| Option | Description |
+| --- | --- |
+| `--seconds-to-run SECONDS` | Nonnegative integer duration in seconds. Defaults to `10`. Set to `0` to run until a stop signal. |
+| `--niter NITER` | Positive integer minimum number of iterations. Defaults to `10`. |
+
+For a finite duration, the benchmark runs until both the duration and minimum iteration count have been reached. For example, run for at least 30 seconds and 100 iterations:
+
+```sh
+python throughput_benchmark.py model.xml CPU --seconds-to-run 30 --niter 100
+```
+
+To run continuously:
+
+```sh
+python throughput_benchmark.py model.xml CPU --seconds-to-run 0
+```
+
+Press Ctrl+C (`SIGINT`) to stop, send `SIGTERM` on Linux or macOS, or press Ctrl+Break (`SIGBREAK`) on Windows. A stop signal ends the run even if `--niter` has not been reached.
+
## Requirements
| Options | Values |
diff --git a/samples/python/benchmark/throughput_benchmark/throughput_benchmark.py b/samples/python/benchmark/throughput_benchmark/throughput_benchmark.py
index 92e1ec82641..a84e8bca1cb 100755
--- a/samples/python/benchmark/throughput_benchmark/throughput_benchmark.py
+++ b/samples/python/benchmark/throughput_benchmark/throughput_benchmark.py
@@ -3,15 +3,36 @@
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
+import argparse
import logging as log
import sys
import statistics
+import signal
+import threading
from time import perf_counter
import numpy as np
import openvino as ov
from openvino.utils.types import get_dtype
+_stop_event = threading.Event()
+
+
+def signal_handler(sig, frame):
+ _stop_event.set()
+
+
+def register_signal_handlers():
+ for name in ('SIGINT', 'SIGTERM', 'SIGBREAK'):
+ sig = getattr(signal, name, None)
+ if sig is None:
+ continue
+ try:
+ signal.signal(sig, signal_handler)
+ except (ValueError, OSError, RuntimeError):
+ # It may throw if not supported not main thread etc.
+ pass
+
def fill_tensor_random(tensor):
dtype = get_dtype(tensor.element_type)
@@ -26,52 +47,74 @@ def fill_tensor_random(tensor):
def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('path_to_model', help='Path to model')
+ parser.add_argument('device_name', nargs='?', default='CPU')
+ parser.add_argument('--seconds-to-run', type=int, default=10, help='Duration in seconds; 0 runs until a stop signal')
+ parser.add_argument('--niter', type=int, default=10, help='Minimum number of iterations')
+ args = parser.parse_args()
+ if args.seconds_to_run < 0 or args.niter < 1:
+ parser.error('--seconds-to-run must be nonnegative and --niter must be positive')
+
log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.INFO, stream=sys.stdout)
log.info('OpenVINO:')
log.info(f"{'Build ':.<39} {ov.__version__}")
- device_name = 'CPU'
- if len(sys.argv) == 3:
- device_name = sys.argv[2]
- elif len(sys.argv) != 2:
- log.info(f'Usage: {sys.argv[0]} <path_to_model> <device_name>(default: CPU)')
- return 1
# Optimize for throughput. Best throughput can be reached by
- # running multiple openvino.InferRequest instances asyncronously
+ # running multiple openvino.InferRequest instances asynchronously
tput = {'PERFORMANCE_HINT': 'THROUGHPUT'}
# Create Core and use it to compile a model.
# Select the device by providing the name as the second parameter to CLI.
# It is possible to set CUMULATIVE_THROUGHPUT as PERFORMANCE_HINT for AUTO device
core = ov.Core()
- compiled_model = core.compile_model(sys.argv[1], device_name, tput)
+ compiled_model = core.compile_model(args.path_to_model, args.device_name, tput)
# AsyncInferQueue creates optimal number of InferRequest instances
ireqs = ov.AsyncInferQueue(compiled_model)
# Fill input data for ireqs
for ireq in ireqs:
for model_input in compiled_model.inputs:
fill_tensor_random(ireq.get_tensor(model_input))
+
# Warm up
for _ in range(len(ireqs)):
ireqs.start_async()
ireqs.wait_all()
+
# Benchmark for seconds_to_run seconds and at least niter iterations
- seconds_to_run = 10
- niter = 10
+ seconds_to_run = args.seconds_to_run
+ niter = args.niter
latencies = []
in_fly = set()
+
+ register_signal_handlers()
+
start = perf_counter()
time_point_to_finish = start + seconds_to_run
- while perf_counter() < time_point_to_finish or len(latencies) + len(in_fly) < niter:
+
+ log.info('Starting inference loop')
+ while seconds_to_run == 0 or perf_counter() < time_point_to_finish or len(latencies) + len(in_fly) < niter:
+ if _stop_event.is_set():
+ log.info('Stop signal received, finishing in-flight requests and reporting stats...')
+ break
+
idle_id = ireqs.get_idle_request_id()
+
if idle_id in in_fly:
latencies.append(ireqs[idle_id].latency)
else:
in_fly.add(idle_id)
+
ireqs.start_async()
+
ireqs.wait_all()
duration = perf_counter() - start
for infer_request_id in in_fly:
latencies.append(ireqs[infer_request_id].latency)
+
+ if not latencies:
+ log.info('No completed iterations to report.')
+ return 0
+
# Report results
fps = len(latencies) / duration
log.info(f'Count: {len(latencies)} iterations')
@@ -83,6 +126,8 @@ def main():
log.info(f' Max: {max(latencies):.2f} ms')
log.info(f'Throughput: {fps:.2f} FPS')
+ return 0
+
if __name__ == '__main__':
main()
diff --git a/tests/samples_tests/smoke_tests/common/samples_common_test_class.py b/tests/samples_tests/smoke_tests/common/samples_common_test_class.py
index 02ae336e049..d876661c45a 100644
--- a/tests/samples_tests/smoke_tests/common/samples_common_test_class.py
+++ b/tests/samples_tests/smoke_tests/common/samples_common_test_class.py
@@ -19,6 +19,7 @@ import io
import os
import itertools
import re
+import signal
import subprocess
import sys
import requests
@@ -50,6 +51,32 @@ def get_cmd_output(*cmd):
return output
+def get_cmd_output_after_signal(*cmd, ready_message, output_path):
+ """Run until a readiness message, then send a stop signal and require a clean exit."""
+ with output_path.open('w', encoding='utf-8') as output_file:
+ process = subprocess.Popen(
+ cmd, stdout=output_file, stderr=subprocess.STDOUT,
+ env={**os.environ, 'PYTHONIOENCODING': 'utf-8'},
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0)
+ try:
+ deadline = time.monotonic() + 60
+ while ready_message not in output_path.read_text(encoding='utf-8'):
+ assert process.poll() is None, output_path.read_text(encoding='utf-8')
+ assert time.monotonic() < deadline, f'Sample did not print {ready_message!r}'
+ time.sleep(0.05)
+ # Allow work to begin and ensure the sample stays alive until signaled.
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ process.wait(timeout=0.5)
+ assert process.poll() is None, output_path.read_text(encoding='utf-8')
+ process.send_signal(signal.CTRL_BREAK_EVENT if os.name == 'nt' else signal.SIGTERM)
+ assert process.wait(timeout=10) == 0, output_path.read_text(encoding='utf-8')
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=10)
+ return output_path.read_text(encoding='utf-8')
+
+
@retry(max_retries=3, exceptions=(requests.RequestException,), delay=5, exponential_backoff=True)
def _requests_get(url):
return requests.get(url)
diff --git a/tests/samples_tests/smoke_tests/test_throughput_benchmark.py b/tests/samples_tests/smoke_tests/test_throughput_benchmark.py
index 52443719ef9..ab045053175 100644
--- a/tests/samples_tests/smoke_tests/test_throughput_benchmark.py
+++ b/tests/samples_tests/smoke_tests/test_throughput_benchmark.py
@@ -1,3 +1,6 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
"""
Copyright (C) 2018-2026 Intel Corporation
Licensed under the Apache License, Version 2.0 (the 'License');
@@ -12,7 +15,12 @@
"""
import os
import sys
-from common.samples_common_test_class import SamplesCommonTestClass
+from pathlib import Path
+
+import openvino as ov
+from openvino import opset8 as opset
+
+from common.samples_common_test_class import SamplesCommonTestClass, get_cmd_output_after_signal
class Test_throughput_benchmark_cpp(SamplesCommonTestClass):
@@ -29,3 +37,19 @@ class Test_throughput_benchmark_py(SamplesCommonTestClass):
def test(self, monkeypatch, cache):
monkeypatch.setenv('PYTHONCOERCECLOCALE', 'warn')
self._test({'m': 'bvlcalexnet-12.onnx'}, cache, use_preffix=False)
+
+ def test_continuous_mode(self, tmp_path):
+ model_path = tmp_path / 'model.xml'
+ model_input = opset.parameter([1, 3, 32, 32], ov.Type.f32)
+
+ ov.save_model(ov.Model([opset.relu(model_input)], [model_input]), model_path)
+
+ sample_path = Path(os.environ['IE_APP_PYTHON_PATH']) / 'benchmark'/ self.sample_name / f'{self.sample_name}.py'
+ output = get_cmd_output_after_signal(
+ sys.executable, '-u', sample_path, model_path, '--seconds-to-run', '0',
+ ready_message='Starting inference loop',
+ output_path=tmp_path / 'throughput.log'
+ )
+
+ assert 'Count:' in output, output
+ assert 'Throughput:' in output, output