py-sharedmemory 2.0.1__tar.gz → 3.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py_sharedmemory-3.0.0/CHANGELOG.md +10 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.0}/LICENSE +1 -1
- py_sharedmemory-3.0.0/MANIFEST.in +4 -0
- py_sharedmemory-3.0.0/PKG-INFO +98 -0
- py_sharedmemory-3.0.0/README.md +73 -0
- py_sharedmemory-3.0.0/benchmarks/__init__.py +1 -0
- py_sharedmemory-3.0.0/benchmarks/benchmark.py +168 -0
- py_sharedmemory-3.0.0/benchmarks/plot.py +80 -0
- py_sharedmemory-3.0.0/benchmarks/results/windows-numpy.json +307 -0
- py_sharedmemory-3.0.0/benchmarks/results/windows-numpy.png +0 -0
- py_sharedmemory-3.0.0/examples/basic.py +39 -0
- py_sharedmemory-3.0.0/memory/__init__.py +7 -0
- py_sharedmemory-3.0.0/memory/convert.py +95 -0
- py_sharedmemory-3.0.0/memory/factory.py +26 -0
- py_sharedmemory-3.0.0/memory/receiver.py +54 -0
- py_sharedmemory-3.0.0/memory/sender.py +231 -0
- py_sharedmemory-3.0.0/py_sharedmemory.egg-info/PKG-INFO +98 -0
- py_sharedmemory-3.0.0/py_sharedmemory.egg-info/SOURCES.txt +30 -0
- py_sharedmemory-3.0.0/py_sharedmemory.egg-info/requires.txt +10 -0
- py_sharedmemory-3.0.0/pyproject.toml +54 -0
- py_sharedmemory-3.0.0/tests/__init__.py +1 -0
- py_sharedmemory-3.0.0/tests/conftest.py +27 -0
- py_sharedmemory-3.0.0/tests/helpers.py +78 -0
- py_sharedmemory-3.0.0/tests/test_benchmark.py +99 -0
- py_sharedmemory-3.0.0/tests/test_convert.py +275 -0
- py_sharedmemory-3.0.0/tests/test_objects.py +91 -0
- py_sharedmemory-3.0.0/tests/test_processes.py +165 -0
- py_sharedmemory-3.0.0/tests/test_queue.py +417 -0
- py_sharedmemory-3.0.0/tests/test_threads.py +116 -0
- py_sharedmemory-2.0.1/PKG-INFO +0 -242
- py_sharedmemory-2.0.1/README.md +0 -226
- py_sharedmemory-2.0.1/memory/__init__.py +0 -3
- py_sharedmemory-2.0.1/memory/convert.py +0 -53
- py_sharedmemory-2.0.1/memory/factory.py +0 -13
- py_sharedmemory-2.0.1/memory/receiver.py +0 -23
- py_sharedmemory-2.0.1/memory/sender.py +0 -111
- py_sharedmemory-2.0.1/py_sharedmemory.egg-info/PKG-INFO +0 -242
- py_sharedmemory-2.0.1/py_sharedmemory.egg-info/SOURCES.txt +0 -12
- py_sharedmemory-2.0.1/pyproject.toml +0 -27
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.0}/py_sharedmemory.egg-info/dependency_links.txt +0 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.0}/py_sharedmemory.egg-info/top_level.txt +0 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.0}/setup.cfg +0 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 3.0.0
|
|
4
|
+
|
|
5
|
+
- Python 3.11+, standard-library-only runtime.
|
|
6
|
+
- Fix acknowledgement races, capacity leaks, failed-put recovery, and process cleanup.
|
|
7
|
+
- Preserve NumPy mutability; remove redundant copies and retained pickle storage.
|
|
8
|
+
- Simplify core ownership and sender flow; use immutable metadata and recover from partial startup.
|
|
9
|
+
- Add explicit close, context managers, context selection, and timed acknowledgement waits.
|
|
10
|
+
- Replace legacy tests and benchmarks; add platform CI and recorded machine results.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: py-sharedmemory
|
|
3
|
+
Version: 3.0.0
|
|
4
|
+
Summary: Shared-memory queues for large Python objects with less pipe I/O
|
|
5
|
+
Author: Tobias Würth
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/tobiaswuerth/python_shared_memory_queue
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/tobiaswuerth/python_shared_memory_queue/issues
|
|
9
|
+
Keywords: queue,multiprocessing,numpy,inter-process-communication,shared-memory
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest>=7.4; extra == "test"
|
|
18
|
+
Requires-Dist: pytest-cov>=4.1; extra == "test"
|
|
19
|
+
Requires-Dist: pytest-timeout>=2.3; extra == "test"
|
|
20
|
+
Requires-Dist: numpy>=1.26; extra == "test"
|
|
21
|
+
Provides-Extra: benchmark
|
|
22
|
+
Requires-Dist: numpy>=1.26; extra == "benchmark"
|
|
23
|
+
Requires-Dist: matplotlib>=3.8; extra == "benchmark"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# py-sharedmemory
|
|
27
|
+
|
|
28
|
+
Send large Python objects between processes with less pipe I/O.
|
|
29
|
+
|
|
30
|
+
Originally built to reduce the heavy Windows pipe I/O and uneven throughput caused by
|
|
31
|
+
large `multiprocessing.Queue` transfers. Payloads travel through shared memory;
|
|
32
|
+
queues carry only small metadata, avoiding bulk transfers through the pipe.
|
|
33
|
+
|
|
34
|
+
Useful for **ML pipelines, reinforcement-learning actors and replay buffers,
|
|
35
|
+
scientific computing, and image/video processing**. Supports pickleable Python
|
|
36
|
+
objects with familiar `put/get` calls. No runtime dependencies. Python 3.11+.
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
pip install py-sharedmemory
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Measured performance
|
|
43
|
+
|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
About **2× faster at 1–10 MB**; **10 GB transferred in 8.0 s**.
|
|
47
|
+
`mp.Queue` failed at 10 GB (Windows error 87). Small messages favor standard queues.
|
|
48
|
+
|
|
49
|
+
Core i9-14900K, 191.8 GiB RAM, Windows 11, Python 3.12.10, NumPy 2.5.3.
|
|
50
|
+
2026-10-08; contiguous float32 arrays; `spawn`; capacity 2; median of 5 runs,
|
|
51
|
+
excluding startup and warmup. Up to 1,000 messages or 512 MiB/run, at least one
|
|
52
|
+
message. GB = 10⁹ bytes. [Raw results](benchmarks/results/windows-numpy.json).
|
|
53
|
+
These measurements show transfer speed; I/O and stability depend on the workload.
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import multiprocessing as mp
|
|
59
|
+
from memory import create_shared_memory_pair
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def produce(sender):
|
|
63
|
+
with sender:
|
|
64
|
+
sender.put({"step": 42, "frames": bytearray(16_000_000)})
|
|
65
|
+
sender.wait_for_all_ack()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
ctx = mp.get_context("spawn")
|
|
70
|
+
sender, receiver = create_shared_memory_pair(capacity=2, ctx=ctx)
|
|
71
|
+
worker = ctx.Process(target=produce, args=(sender,))
|
|
72
|
+
worker.start()
|
|
73
|
+
with receiver:
|
|
74
|
+
batch = receiver.get(timeout=30)
|
|
75
|
+
worker.join()
|
|
76
|
+
sender.close()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
One producing process per pair; multiple threads and consumers are supported.
|
|
80
|
+
Pass endpoints to workers before use. `put/get` support `block`, `timeout`, and
|
|
81
|
+
`*_nowait`. Capacity counts outstanding messages; 0/`None` is unbounded.
|
|
82
|
+
|
|
83
|
+
**Drain before producer close or exit:** `wait_for_all_ack(timeout=...)` returns
|
|
84
|
+
`False` on timeout. Close discards unread data. Within one process, drain before
|
|
85
|
+
closing either endpoint. Received data stays valid after cleanup; arrays preserve mutability.
|
|
86
|
+
|
|
87
|
+
A [complete example](examples/basic.py) includes error handling.
|
|
88
|
+
|
|
89
|
+
## Test and benchmark
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
python -m pip install -e ".[test,benchmark]"
|
|
93
|
+
python -m pytest --cov=memory
|
|
94
|
+
python -m benchmarks.benchmark --sizes 16 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 --repeats 5 --json benchmarks/results/windows-numpy.json
|
|
95
|
+
python -m benchmarks.plot benchmarks/results/windows-numpy.json benchmarks/results/windows-numpy.png
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The full benchmark needs enough RAM for several payload copies.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# py-sharedmemory
|
|
2
|
+
|
|
3
|
+
Send large Python objects between processes with less pipe I/O.
|
|
4
|
+
|
|
5
|
+
Originally built to reduce the heavy Windows pipe I/O and uneven throughput caused by
|
|
6
|
+
large `multiprocessing.Queue` transfers. Payloads travel through shared memory;
|
|
7
|
+
queues carry only small metadata, avoiding bulk transfers through the pipe.
|
|
8
|
+
|
|
9
|
+
Useful for **ML pipelines, reinforcement-learning actors and replay buffers,
|
|
10
|
+
scientific computing, and image/video processing**. Supports pickleable Python
|
|
11
|
+
objects with familiar `put/get` calls. No runtime dependencies. Python 3.11+.
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pip install py-sharedmemory
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Measured performance
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+
|
|
21
|
+
About **2× faster at 1–10 MB**; **10 GB transferred in 8.0 s**.
|
|
22
|
+
`mp.Queue` failed at 10 GB (Windows error 87). Small messages favor standard queues.
|
|
23
|
+
|
|
24
|
+
Core i9-14900K, 191.8 GiB RAM, Windows 11, Python 3.12.10, NumPy 2.5.3.
|
|
25
|
+
2026-10-08; contiguous float32 arrays; `spawn`; capacity 2; median of 5 runs,
|
|
26
|
+
excluding startup and warmup. Up to 1,000 messages or 512 MiB/run, at least one
|
|
27
|
+
message. GB = 10⁹ bytes. [Raw results](benchmarks/results/windows-numpy.json).
|
|
28
|
+
These measurements show transfer speed; I/O and stability depend on the workload.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import multiprocessing as mp
|
|
34
|
+
from memory import create_shared_memory_pair
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def produce(sender):
|
|
38
|
+
with sender:
|
|
39
|
+
sender.put({"step": 42, "frames": bytearray(16_000_000)})
|
|
40
|
+
sender.wait_for_all_ack()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == "__main__":
|
|
44
|
+
ctx = mp.get_context("spawn")
|
|
45
|
+
sender, receiver = create_shared_memory_pair(capacity=2, ctx=ctx)
|
|
46
|
+
worker = ctx.Process(target=produce, args=(sender,))
|
|
47
|
+
worker.start()
|
|
48
|
+
with receiver:
|
|
49
|
+
batch = receiver.get(timeout=30)
|
|
50
|
+
worker.join()
|
|
51
|
+
sender.close()
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
One producing process per pair; multiple threads and consumers are supported.
|
|
55
|
+
Pass endpoints to workers before use. `put/get` support `block`, `timeout`, and
|
|
56
|
+
`*_nowait`. Capacity counts outstanding messages; 0/`None` is unbounded.
|
|
57
|
+
|
|
58
|
+
**Drain before producer close or exit:** `wait_for_all_ack(timeout=...)` returns
|
|
59
|
+
`False` on timeout. Close discards unread data. Within one process, drain before
|
|
60
|
+
closing either endpoint. Received data stays valid after cleanup; arrays preserve mutability.
|
|
61
|
+
|
|
62
|
+
A [complete example](examples/basic.py) includes error handling.
|
|
63
|
+
|
|
64
|
+
## Test and benchmark
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
python -m pip install -e ".[test,benchmark]"
|
|
68
|
+
python -m pytest --cov=memory
|
|
69
|
+
python -m benchmarks.benchmark --sizes 16 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 --repeats 5 --json benchmarks/results/windows-numpy.json
|
|
70
|
+
python -m benchmarks.plot benchmarks/results/windows-numpy.json benchmarks/results/windows-numpy.png
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The full benchmark needs enough RAM for several payload copies.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Opt-in throughput measurements; excluded from the installed package."""
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Compare real process-to-process throughput with multiprocessing.Queue."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
import multiprocessing as mp
|
|
7
|
+
import platform
|
|
8
|
+
import statistics
|
|
9
|
+
import time
|
|
10
|
+
from contextlib import redirect_stderr
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from memory import create_shared_memory_pair
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _receive(receiver, count, warmup, control, size):
|
|
18
|
+
try:
|
|
19
|
+
for _ in range(warmup):
|
|
20
|
+
receiver.get(timeout=30)
|
|
21
|
+
control.send("ready")
|
|
22
|
+
if control.recv() != "start":
|
|
23
|
+
raise RuntimeError("Invalid benchmark handshake")
|
|
24
|
+
for _ in range(count):
|
|
25
|
+
payload = receiver.get(timeout=30)
|
|
26
|
+
actual_size = payload.nbytes if hasattr(payload, "nbytes") else len(payload)
|
|
27
|
+
if actual_size != size:
|
|
28
|
+
raise ValueError("Received the wrong payload size")
|
|
29
|
+
control.send("done")
|
|
30
|
+
except Exception as error:
|
|
31
|
+
control.send({"error": f"{type(error).__name__}: {error}"})
|
|
32
|
+
finally:
|
|
33
|
+
receiver.close()
|
|
34
|
+
control.close()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _expect(control, expected):
|
|
38
|
+
if not control.poll(30):
|
|
39
|
+
raise TimeoutError(f"Benchmark consumer did not signal {expected}")
|
|
40
|
+
message = control.recv()
|
|
41
|
+
if isinstance(message, dict) and "error" in message:
|
|
42
|
+
raise RuntimeError(f"Consumer failed: {message['error']}")
|
|
43
|
+
if message != expected:
|
|
44
|
+
raise RuntimeError("Invalid benchmark handshake")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def measure(transport, payload, count, capacity, ctx):
|
|
48
|
+
"""Measure after process startup and warmup, through the last received item."""
|
|
49
|
+
size = payload.nbytes if hasattr(payload, "nbytes") else len(payload)
|
|
50
|
+
if transport == "shared":
|
|
51
|
+
sender, receiver = create_shared_memory_pair(capacity, ctx=ctx)
|
|
52
|
+
else:
|
|
53
|
+
sender = receiver = ctx.Queue(maxsize=capacity)
|
|
54
|
+
control, child_control = ctx.Pipe()
|
|
55
|
+
warmup = min(3, count)
|
|
56
|
+
process = ctx.Process(target=_receive, args=(receiver, count, warmup, child_control, size))
|
|
57
|
+
process.start()
|
|
58
|
+
child_control.close()
|
|
59
|
+
try:
|
|
60
|
+
for _ in range(warmup):
|
|
61
|
+
sender.put(payload, timeout=30)
|
|
62
|
+
_expect(control, "ready")
|
|
63
|
+
if transport == "shared" and not sender.wait_for_all_ack(timeout=30):
|
|
64
|
+
raise TimeoutError("Warmup messages were not acknowledged")
|
|
65
|
+
start = time.perf_counter()
|
|
66
|
+
control.send("start")
|
|
67
|
+
for _ in range(count):
|
|
68
|
+
sender.put(payload, timeout=30)
|
|
69
|
+
_expect(control, "done")
|
|
70
|
+
if transport == "shared" and not sender.wait_for_all_ack(timeout=30):
|
|
71
|
+
raise TimeoutError("Benchmark messages were not acknowledged")
|
|
72
|
+
duration = time.perf_counter() - start
|
|
73
|
+
process.join(10)
|
|
74
|
+
if process.is_alive() or process.exitcode != 0:
|
|
75
|
+
raise RuntimeError("Benchmark consumer failed")
|
|
76
|
+
return duration
|
|
77
|
+
finally:
|
|
78
|
+
if process.is_alive():
|
|
79
|
+
process.terminate()
|
|
80
|
+
process.join(5)
|
|
81
|
+
control.close()
|
|
82
|
+
if transport == "shared":
|
|
83
|
+
sender.close()
|
|
84
|
+
receiver.close()
|
|
85
|
+
else:
|
|
86
|
+
sender.cancel_join_thread()
|
|
87
|
+
sender.close()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _positive_int(value):
|
|
91
|
+
number = int(value)
|
|
92
|
+
if number <= 0:
|
|
93
|
+
raise argparse.ArgumentTypeError("must be positive")
|
|
94
|
+
return number
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def main(argv=None):
|
|
98
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
99
|
+
parser.add_argument("--sizes", nargs="+", type=_positive_int, default=[1_024, 2**20, 2**24])
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--messages", type=_positive_int, help="default: up to 1,000 or 512 MiB/run"
|
|
102
|
+
)
|
|
103
|
+
parser.add_argument("--capacity", type=_positive_int, default=2)
|
|
104
|
+
parser.add_argument("--repeats", type=_positive_int, default=3)
|
|
105
|
+
parser.add_argument("--payload", choices=["numpy", "bytes"], default="numpy")
|
|
106
|
+
parser.add_argument("--start-method", choices=mp.get_all_start_methods(), default="spawn")
|
|
107
|
+
parser.add_argument("--json", type=Path, help="optional result file")
|
|
108
|
+
args = parser.parse_args(argv)
|
|
109
|
+
if args.payload == "numpy" and any(size % 4 for size in args.sizes):
|
|
110
|
+
parser.error("NumPy sizes must be multiples of 4 for float32 payloads")
|
|
111
|
+
if args.payload == "numpy":
|
|
112
|
+
import numpy as np
|
|
113
|
+
|
|
114
|
+
ctx = mp.get_context(args.start_method)
|
|
115
|
+
results = []
|
|
116
|
+
report = {
|
|
117
|
+
"generated_at_utc": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
118
|
+
"python": platform.python_version(),
|
|
119
|
+
"platform": platform.platform(),
|
|
120
|
+
"processor": platform.processor(),
|
|
121
|
+
"start_method": args.start_method,
|
|
122
|
+
"capacity": args.capacity,
|
|
123
|
+
"payload": args.payload,
|
|
124
|
+
"numpy": np.__version__ if args.payload == "numpy" else None,
|
|
125
|
+
"repeats": args.repeats,
|
|
126
|
+
"results": results,
|
|
127
|
+
}
|
|
128
|
+
print(f"Payload: {args.payload}; start method: {args.start_method}; capacity: {args.capacity}")
|
|
129
|
+
print(f"{'Bytes':>12} {'Transport':>9} {'MiB/s':>10} {'ms/message':>12}")
|
|
130
|
+
for size in args.sizes:
|
|
131
|
+
count = args.messages or min(1_000, max(1, 2**29 // size))
|
|
132
|
+
if args.payload == "numpy":
|
|
133
|
+
payload = np.ones(size // 4, dtype=np.float32)
|
|
134
|
+
else:
|
|
135
|
+
payload = b"x" * size
|
|
136
|
+
for transport in ("standard", "shared"):
|
|
137
|
+
row = {"transport": transport, "size": size, "messages": count}
|
|
138
|
+
durations = []
|
|
139
|
+
diagnostics = io.StringIO()
|
|
140
|
+
try:
|
|
141
|
+
with redirect_stderr(diagnostics):
|
|
142
|
+
for _ in range(args.repeats):
|
|
143
|
+
durations.append(measure(transport, payload, count, args.capacity, ctx))
|
|
144
|
+
except Exception as error:
|
|
145
|
+
row.update(status="failed", error=f"{type(error).__name__}: {error}")
|
|
146
|
+
if diagnostics.getvalue():
|
|
147
|
+
row["stderr"] = diagnostics.getvalue()
|
|
148
|
+
print(f"{size:12,d} {transport:>9} FAILED: {row['error']}", flush=True)
|
|
149
|
+
else:
|
|
150
|
+
duration = statistics.median(durations)
|
|
151
|
+
throughput = size * count / duration / 2**20
|
|
152
|
+
latency = duration * 1_000 / count
|
|
153
|
+
row.update(
|
|
154
|
+
status="ok",
|
|
155
|
+
median_mib_per_second=throughput,
|
|
156
|
+
median_ms_per_message=latency,
|
|
157
|
+
)
|
|
158
|
+
print(
|
|
159
|
+
f"{size:12,d} {transport:>9} {throughput:10.1f} {latency:12.3f}", flush=True
|
|
160
|
+
)
|
|
161
|
+
row["durations_seconds"] = durations
|
|
162
|
+
results.append(row)
|
|
163
|
+
if args.json:
|
|
164
|
+
args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
if __name__ == "__main__":
|
|
168
|
+
main()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Plot the recorded benchmark without inventing throughput for failed transfers."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import matplotlib
|
|
8
|
+
|
|
9
|
+
matplotlib.use("Agg")
|
|
10
|
+
import matplotlib.pyplot as plt # noqa: E402
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def plot(report, output):
|
|
14
|
+
plt.rcParams.update({"font.size": 11, "font.family": "DejaVu Sans"})
|
|
15
|
+
shared = {r["size"]: r for r in report["results"] if r["transport"] == "shared"}
|
|
16
|
+
standard = {r["size"]: r for r in report["results"] if r["transport"] == "standard"}
|
|
17
|
+
sizes = sorted(s for s in shared if shared[s]["status"] == standard[s]["status"] == "ok")
|
|
18
|
+
ratios = [
|
|
19
|
+
shared[s]["median_mib_per_second"] / standard[s]["median_mib_per_second"] for s in sizes
|
|
20
|
+
]
|
|
21
|
+
failures = [
|
|
22
|
+
s for s in shared if shared[s]["status"] == "ok" and standard[s]["status"] == "failed"
|
|
23
|
+
]
|
|
24
|
+
fig, axes = plt.subplots(
|
|
25
|
+
1,
|
|
26
|
+
2 if failures else 1,
|
|
27
|
+
figsize=(11, 4.5),
|
|
28
|
+
gridspec_kw={"width_ratios": [4, 1]} if failures else None,
|
|
29
|
+
layout="constrained",
|
|
30
|
+
squeeze=False,
|
|
31
|
+
)
|
|
32
|
+
ax = axes[0, 0]
|
|
33
|
+
bars = ax.bar(
|
|
34
|
+
range(len(sizes)),
|
|
35
|
+
ratios,
|
|
36
|
+
width=0.7,
|
|
37
|
+
color=["#0d9488" if ratio >= 1 else "#94a3b8" for ratio in ratios],
|
|
38
|
+
)
|
|
39
|
+
ax.bar_label(bars, labels=[f"{ratio:.2f}×" for ratio in ratios], padding=5, fontsize=10)
|
|
40
|
+
ax.axhline(1, color="#64748b", linestyle="--", linewidth=1.2)
|
|
41
|
+
ax.text(0.01, 1.05, "Standard queue (1×)", transform=ax.get_yaxis_transform(), fontsize=9)
|
|
42
|
+
ax.set_xticks(range(len(sizes)))
|
|
43
|
+
ax.set_xticklabels([_size_label(size) for size in sizes])
|
|
44
|
+
ax.set_ylim(0, max(2.5, max(ratios, default=1) * 1.2))
|
|
45
|
+
ax.set_xlabel("Payload per message")
|
|
46
|
+
ax.set_ylabel("Speedup · higher is better")
|
|
47
|
+
ax.set_title("Transfer speed vs. multiprocessing.Queue", loc="left", fontweight="bold", pad=18)
|
|
48
|
+
ax.grid(axis="y", color="#e2e8f0", linewidth=0.8)
|
|
49
|
+
ax.set_axisbelow(True)
|
|
50
|
+
ax.spines[["top", "right"]].set_visible(False)
|
|
51
|
+
if failures:
|
|
52
|
+
panel = axes[0, 1]
|
|
53
|
+
panel.axis("off")
|
|
54
|
+
size = max(failures)
|
|
55
|
+
seconds = shared[size]["median_ms_per_message"] / 1_000
|
|
56
|
+
panel.text(0.5, 0.86, f"{_size_label(size)} payload", ha="center", fontweight="bold")
|
|
57
|
+
panel.text(0.5, 0.63, f"{seconds:.1f} s", ha="center", fontsize=30, color="#0d9488")
|
|
58
|
+
panel.text(0.5, 0.5, "py-sharedmemory", ha="center")
|
|
59
|
+
panel.text(0.5, 0.25, "mp.Queue failed", ha="center", color="#b91c1c")
|
|
60
|
+
fig.savefig(output, dpi=200, facecolor="white")
|
|
61
|
+
plt.close(fig)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _size_label(size):
|
|
65
|
+
for divisor, unit in ((10**9, "GB"), (10**6, "MB"), (10**3, "kB")):
|
|
66
|
+
if size >= divisor:
|
|
67
|
+
return f"{size / divisor:g} {unit}"
|
|
68
|
+
return f"{size} B"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def main():
|
|
72
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
73
|
+
parser.add_argument("results", type=Path)
|
|
74
|
+
parser.add_argument("output", type=Path)
|
|
75
|
+
args = parser.parse_args()
|
|
76
|
+
plot(json.loads(args.results.read_text(encoding="utf-8")), args.output)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
main()
|