py-sharedmemory 2.0.1__tar.gz → 3.0.1__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.1/CHANGELOG.md +20 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.1}/LICENSE +21 -21
- py_sharedmemory-3.0.1/MANIFEST.in +4 -0
- py_sharedmemory-3.0.1/PKG-INFO +155 -0
- py_sharedmemory-3.0.1/README.md +107 -0
- py_sharedmemory-3.0.1/benchmarks/__init__.py +1 -0
- py_sharedmemory-3.0.1/benchmarks/benchmark.py +165 -0
- py_sharedmemory-3.0.1/benchmarks/plot.py +80 -0
- py_sharedmemory-3.0.1/benchmarks/results/windows-numpy.json +307 -0
- py_sharedmemory-3.0.1/benchmarks/results/windows-numpy.png +0 -0
- py_sharedmemory-3.0.1/examples/basic.py +39 -0
- py_sharedmemory-3.0.1/memory/__init__.py +8 -0
- py_sharedmemory-3.0.1/memory/convert.py +101 -0
- py_sharedmemory-3.0.1/memory/factory.py +34 -0
- py_sharedmemory-3.0.1/memory/py.typed +0 -0
- py_sharedmemory-3.0.1/memory/receiver.py +62 -0
- py_sharedmemory-3.0.1/memory/sender.py +242 -0
- py_sharedmemory-3.0.1/py_sharedmemory.egg-info/PKG-INFO +155 -0
- py_sharedmemory-3.0.1/py_sharedmemory.egg-info/SOURCES.txt +32 -0
- py_sharedmemory-3.0.1/py_sharedmemory.egg-info/requires.txt +18 -0
- py_sharedmemory-3.0.1/pyproject.toml +100 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.1}/setup.cfg +4 -4
- py_sharedmemory-3.0.1/tests/__init__.py +1 -0
- py_sharedmemory-3.0.1/tests/conftest.py +27 -0
- py_sharedmemory-3.0.1/tests/helpers.py +78 -0
- py_sharedmemory-3.0.1/tests/test_benchmark.py +133 -0
- py_sharedmemory-3.0.1/tests/test_convert.py +303 -0
- py_sharedmemory-3.0.1/tests/test_objects.py +91 -0
- py_sharedmemory-3.0.1/tests/test_package.py +34 -0
- py_sharedmemory-3.0.1/tests/test_processes.py +203 -0
- py_sharedmemory-3.0.1/tests/test_queue.py +473 -0
- py_sharedmemory-3.0.1/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.1}/py_sharedmemory.egg-info/dependency_links.txt +0 -0
- {py_sharedmemory-2.0.1 → py_sharedmemory-3.0.1}/py_sharedmemory.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 3.0.1
|
|
4
|
+
|
|
5
|
+
- Fix resource-tracker leaks on Linux and macOS: receivers no longer register blocks they
|
|
6
|
+
attach to, so `fork` workers no longer accumulate tracker entries or print
|
|
7
|
+
"leaked shared_memory" warnings at exit.
|
|
8
|
+
- Ship type hints (`py.typed`), checked with strict mypy; expose `memory.__version__`.
|
|
9
|
+
- Support and test Python 3.15; test Linux, macOS, and Windows for every Python version.
|
|
10
|
+
- Require 100% branch coverage; add pre-commit hooks, Dependabot, and a trusted-publishing
|
|
11
|
+
release workflow.
|
|
12
|
+
|
|
13
|
+
## 3.0.0
|
|
14
|
+
|
|
15
|
+
- Python 3.11+, standard-library-only runtime.
|
|
16
|
+
- Fix acknowledgement races, capacity leaks, failed-put recovery, and process cleanup.
|
|
17
|
+
- Preserve NumPy mutability; remove redundant copies and retained pickle storage.
|
|
18
|
+
- Simplify core ownership and sender flow; use immutable metadata and recover from partial startup.
|
|
19
|
+
- Add explicit close, context managers, context selection, and timed acknowledgement waits.
|
|
20
|
+
- Replace legacy tests and benchmarks; add platform CI and recorded machine results.
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c)
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tobias Würth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: py-sharedmemory
|
|
3
|
+
Version: 3.0.1
|
|
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: Homepage, https://github.com/tobiaswuerth/python_shared_memory_queue
|
|
8
|
+
Project-URL: Repository, https://github.com/tobiaswuerth/python_shared_memory_queue
|
|
9
|
+
Project-URL: Changelog, https://github.com/tobiaswuerth/python_shared_memory_queue/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/tobiaswuerth/python_shared_memory_queue/issues
|
|
11
|
+
Keywords: queue,multiprocessing,shared-memory,inter-process-communication,ipc,numpy,zero-copy,pickle
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: MacOS
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Python: >=3.11
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
License-File: LICENSE
|
|
32
|
+
Provides-Extra: test
|
|
33
|
+
Requires-Dist: pytest>=7.4; extra == "test"
|
|
34
|
+
Requires-Dist: pytest-cov>=4.1; extra == "test"
|
|
35
|
+
Requires-Dist: pytest-timeout>=2.3; extra == "test"
|
|
36
|
+
Requires-Dist: numpy>=1.26; extra == "test"
|
|
37
|
+
Provides-Extra: benchmark
|
|
38
|
+
Requires-Dist: numpy>=1.26; extra == "benchmark"
|
|
39
|
+
Requires-Dist: matplotlib>=3.8; extra == "benchmark"
|
|
40
|
+
Provides-Extra: dev
|
|
41
|
+
Requires-Dist: py-sharedmemory[benchmark,test]; extra == "dev"
|
|
42
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
43
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
44
|
+
Requires-Dist: pre-commit>=3.7; extra == "dev"
|
|
45
|
+
Requires-Dist: ruff>=0.15; extra == "dev"
|
|
46
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# py-sharedmemory
|
|
50
|
+
|
|
51
|
+
[](https://github.com/tobiaswuerth/python_shared_memory_queue/actions/workflows/ci.yml)
|
|
52
|
+
[](https://pypi.org/project/py-sharedmemory/)
|
|
53
|
+
[](https://pypi.org/project/py-sharedmemory/)
|
|
54
|
+
[](https://pypistats.org/packages/py-sharedmemory)
|
|
55
|
+
[](https://github.com/tobiaswuerth/python_shared_memory_queue/actions/workflows/ci.yml)
|
|
56
|
+
[](LICENSE)
|
|
57
|
+
[](https://github.com/astral-sh/ruff)
|
|
58
|
+
[](https://mypy-lang.org/)
|
|
59
|
+
[](https://github.com/pre-commit/pre-commit)
|
|
60
|
+
|
|
61
|
+
Send large Python objects between processes with less pipe I/O.
|
|
62
|
+
|
|
63
|
+
Originally built to reduce the heavy Windows pipe I/O and uneven throughput caused by
|
|
64
|
+
large `multiprocessing.Queue` transfers. Payloads travel through shared memory;
|
|
65
|
+
queues carry only small metadata, avoiding bulk transfers through the pipe.
|
|
66
|
+
|
|
67
|
+
Useful for **ML pipelines, reinforcement-learning actors and replay buffers,
|
|
68
|
+
scientific computing, and image/video processing**. Supports pickleable Python
|
|
69
|
+
objects with familiar `put/get` calls. No runtime dependencies, fully typed.
|
|
70
|
+
Python 3.11+ on Linux, macOS, and Windows.
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
pip install py-sharedmemory
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Measured performance
|
|
77
|
+
|
|
78
|
+

|
|
79
|
+
|
|
80
|
+
About **2× faster at 1–10 MB**; **10 GB transferred in 8.0 s**.
|
|
81
|
+
`mp.Queue` failed at 10 GB (Windows error 87). Small messages favor standard queues.
|
|
82
|
+
|
|
83
|
+
Core i9-14900K, 191.8 GiB RAM, Windows 11, Python 3.12.10, NumPy 2.5.3.
|
|
84
|
+
2026-10-08; contiguous float32 arrays; `spawn`; capacity 2; median of 5 runs,
|
|
85
|
+
excluding startup and warmup. Up to 1,000 messages or 512 MiB/run, at least one
|
|
86
|
+
message. GB = 10⁹ bytes. [Raw results](benchmarks/results/windows-numpy.json).
|
|
87
|
+
These measurements show transfer speed; I/O and stability depend on the workload.
|
|
88
|
+
|
|
89
|
+
## Usage
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import multiprocessing as mp
|
|
93
|
+
from memory import create_shared_memory_pair
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def produce(sender):
|
|
97
|
+
with sender:
|
|
98
|
+
sender.put({"step": 42, "frames": bytearray(16_000_000)})
|
|
99
|
+
sender.wait_for_all_ack()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
ctx = mp.get_context("spawn")
|
|
104
|
+
sender, receiver = create_shared_memory_pair(capacity=2, ctx=ctx)
|
|
105
|
+
worker = ctx.Process(target=produce, args=(sender,))
|
|
106
|
+
worker.start()
|
|
107
|
+
with receiver:
|
|
108
|
+
batch = receiver.get(timeout=30)
|
|
109
|
+
worker.join()
|
|
110
|
+
sender.close()
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
One producing process per pair; multiple threads and consumers are supported.
|
|
114
|
+
Pass endpoints to workers before use. `put/get` support `block`, `timeout`, and
|
|
115
|
+
`*_nowait`. Capacity counts outstanding messages; 0/`None` is unbounded.
|
|
116
|
+
|
|
117
|
+
**Drain before producer close or exit:** `wait_for_all_ack(timeout=...)` returns
|
|
118
|
+
`False` on timeout. Close discards unread data. Within one process, drain before
|
|
119
|
+
closing either endpoint. Received data stays valid after cleanup; arrays preserve mutability.
|
|
120
|
+
|
|
121
|
+
A [complete example](examples/basic.py) includes error handling.
|
|
122
|
+
|
|
123
|
+
### API
|
|
124
|
+
|
|
125
|
+
| Call | Behavior |
|
|
126
|
+
| --- | --- |
|
|
127
|
+
| `create_shared_memory_pair(capacity=0, *, ctx=None)` | Returns `(sender, receiver)` built from one multiprocessing context. |
|
|
128
|
+
| `sender.put(obj, block=True, timeout=None)` / `put_nowait(obj)` | Copies `obj` into a new shared-memory block; raises `queue.Full`. |
|
|
129
|
+
| `sender.wait_for_all_ack(timeout=None)` | Waits until every block is received and freed; `False` on timeout. |
|
|
130
|
+
| `receiver.get(block=True, timeout=None)` / `get_nowait()` | Returns an independent local copy; raises `queue.Empty`. |
|
|
131
|
+
| `close()`, `closed`, `with endpoint:` | Both endpoints; using a closed endpoint raises `BrokenPipeError`. |
|
|
132
|
+
|
|
133
|
+
## Development
|
|
134
|
+
|
|
135
|
+
```sh
|
|
136
|
+
python -m pip install -e ".[dev]"
|
|
137
|
+
pre-commit install
|
|
138
|
+
python -m pytest --cov
|
|
139
|
+
pre-commit run --all-files
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
CI runs the tests on Linux, macOS, and Windows with Python 3.11–3.15 and requires
|
|
143
|
+
100% branch coverage on each. Pre-commit runs Ruff, mypy (strict), and file checks.
|
|
144
|
+
|
|
145
|
+
To release, update `__version__` in `memory/__init__.py` and the changelog, then
|
|
146
|
+
publish a GitHub release tagged `vX.Y.Z`. The release workflow uploads it to PyPI.
|
|
147
|
+
|
|
148
|
+
### Benchmark
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
python -m benchmarks.benchmark --sizes 16 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 --repeats 5 --json benchmarks/results/windows-numpy.json
|
|
152
|
+
python -m benchmarks.plot benchmarks/results/windows-numpy.json benchmarks/results/windows-numpy.png
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The full benchmark needs enough RAM for several payload copies.
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# py-sharedmemory
|
|
2
|
+
|
|
3
|
+
[](https://github.com/tobiaswuerth/python_shared_memory_queue/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/py-sharedmemory/)
|
|
5
|
+
[](https://pypi.org/project/py-sharedmemory/)
|
|
6
|
+
[](https://pypistats.org/packages/py-sharedmemory)
|
|
7
|
+
[](https://github.com/tobiaswuerth/python_shared_memory_queue/actions/workflows/ci.yml)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](https://github.com/astral-sh/ruff)
|
|
10
|
+
[](https://mypy-lang.org/)
|
|
11
|
+
[](https://github.com/pre-commit/pre-commit)
|
|
12
|
+
|
|
13
|
+
Send large Python objects between processes with less pipe I/O.
|
|
14
|
+
|
|
15
|
+
Originally built to reduce the heavy Windows pipe I/O and uneven throughput caused by
|
|
16
|
+
large `multiprocessing.Queue` transfers. Payloads travel through shared memory;
|
|
17
|
+
queues carry only small metadata, avoiding bulk transfers through the pipe.
|
|
18
|
+
|
|
19
|
+
Useful for **ML pipelines, reinforcement-learning actors and replay buffers,
|
|
20
|
+
scientific computing, and image/video processing**. Supports pickleable Python
|
|
21
|
+
objects with familiar `put/get` calls. No runtime dependencies, fully typed.
|
|
22
|
+
Python 3.11+ on Linux, macOS, and Windows.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pip install py-sharedmemory
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Measured performance
|
|
29
|
+
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
About **2× faster at 1–10 MB**; **10 GB transferred in 8.0 s**.
|
|
33
|
+
`mp.Queue` failed at 10 GB (Windows error 87). Small messages favor standard queues.
|
|
34
|
+
|
|
35
|
+
Core i9-14900K, 191.8 GiB RAM, Windows 11, Python 3.12.10, NumPy 2.5.3.
|
|
36
|
+
2026-10-08; contiguous float32 arrays; `spawn`; capacity 2; median of 5 runs,
|
|
37
|
+
excluding startup and warmup. Up to 1,000 messages or 512 MiB/run, at least one
|
|
38
|
+
message. GB = 10⁹ bytes. [Raw results](benchmarks/results/windows-numpy.json).
|
|
39
|
+
These measurements show transfer speed; I/O and stability depend on the workload.
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import multiprocessing as mp
|
|
45
|
+
from memory import create_shared_memory_pair
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def produce(sender):
|
|
49
|
+
with sender:
|
|
50
|
+
sender.put({"step": 42, "frames": bytearray(16_000_000)})
|
|
51
|
+
sender.wait_for_all_ack()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
if __name__ == "__main__":
|
|
55
|
+
ctx = mp.get_context("spawn")
|
|
56
|
+
sender, receiver = create_shared_memory_pair(capacity=2, ctx=ctx)
|
|
57
|
+
worker = ctx.Process(target=produce, args=(sender,))
|
|
58
|
+
worker.start()
|
|
59
|
+
with receiver:
|
|
60
|
+
batch = receiver.get(timeout=30)
|
|
61
|
+
worker.join()
|
|
62
|
+
sender.close()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
One producing process per pair; multiple threads and consumers are supported.
|
|
66
|
+
Pass endpoints to workers before use. `put/get` support `block`, `timeout`, and
|
|
67
|
+
`*_nowait`. Capacity counts outstanding messages; 0/`None` is unbounded.
|
|
68
|
+
|
|
69
|
+
**Drain before producer close or exit:** `wait_for_all_ack(timeout=...)` returns
|
|
70
|
+
`False` on timeout. Close discards unread data. Within one process, drain before
|
|
71
|
+
closing either endpoint. Received data stays valid after cleanup; arrays preserve mutability.
|
|
72
|
+
|
|
73
|
+
A [complete example](examples/basic.py) includes error handling.
|
|
74
|
+
|
|
75
|
+
### API
|
|
76
|
+
|
|
77
|
+
| Call | Behavior |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `create_shared_memory_pair(capacity=0, *, ctx=None)` | Returns `(sender, receiver)` built from one multiprocessing context. |
|
|
80
|
+
| `sender.put(obj, block=True, timeout=None)` / `put_nowait(obj)` | Copies `obj` into a new shared-memory block; raises `queue.Full`. |
|
|
81
|
+
| `sender.wait_for_all_ack(timeout=None)` | Waits until every block is received and freed; `False` on timeout. |
|
|
82
|
+
| `receiver.get(block=True, timeout=None)` / `get_nowait()` | Returns an independent local copy; raises `queue.Empty`. |
|
|
83
|
+
| `close()`, `closed`, `with endpoint:` | Both endpoints; using a closed endpoint raises `BrokenPipeError`. |
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
python -m pip install -e ".[dev]"
|
|
89
|
+
pre-commit install
|
|
90
|
+
python -m pytest --cov
|
|
91
|
+
pre-commit run --all-files
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
CI runs the tests on Linux, macOS, and Windows with Python 3.11–3.15 and requires
|
|
95
|
+
100% branch coverage on each. Pre-commit runs Ruff, mypy (strict), and file checks.
|
|
96
|
+
|
|
97
|
+
To release, update `__version__` in `memory/__init__.py` and the changelog, then
|
|
98
|
+
publish a GitHub release tagged `vX.Y.Z`. The release workflow uploads it to PyPI.
|
|
99
|
+
|
|
100
|
+
### Benchmark
|
|
101
|
+
|
|
102
|
+
```sh
|
|
103
|
+
python -m benchmarks.benchmark --sizes 16 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 --repeats 5 --json benchmarks/results/windows-numpy.json
|
|
104
|
+
python -m benchmarks.plot benchmarks/results/windows-numpy.json benchmarks/results/windows-numpy.png
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
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,165 @@
|
|
|
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
|
+
payload = np.ones(size // 4, dtype=np.float32) if args.payload == "numpy" else b"x" * size
|
|
133
|
+
for transport in ("standard", "shared"):
|
|
134
|
+
row = {"transport": transport, "size": size, "messages": count}
|
|
135
|
+
durations = []
|
|
136
|
+
diagnostics = io.StringIO()
|
|
137
|
+
try:
|
|
138
|
+
with redirect_stderr(diagnostics):
|
|
139
|
+
for _ in range(args.repeats):
|
|
140
|
+
durations.append(measure(transport, payload, count, args.capacity, ctx))
|
|
141
|
+
except Exception as error:
|
|
142
|
+
row.update(status="failed", error=f"{type(error).__name__}: {error}")
|
|
143
|
+
if diagnostics.getvalue():
|
|
144
|
+
row["stderr"] = diagnostics.getvalue()
|
|
145
|
+
print(f"{size:12,d} {transport:>9} FAILED: {row['error']}", flush=True)
|
|
146
|
+
else:
|
|
147
|
+
duration = statistics.median(durations)
|
|
148
|
+
throughput = size * count / duration / 2**20
|
|
149
|
+
latency = duration * 1_000 / count
|
|
150
|
+
row.update(
|
|
151
|
+
status="ok",
|
|
152
|
+
median_mib_per_second=throughput,
|
|
153
|
+
median_ms_per_message=latency,
|
|
154
|
+
)
|
|
155
|
+
print(
|
|
156
|
+
f"{size:12,d} {transport:>9} {throughput:10.1f} {latency:12.3f}", flush=True
|
|
157
|
+
)
|
|
158
|
+
row["durations_seconds"] = durations
|
|
159
|
+
results.append(row)
|
|
160
|
+
if args.json:
|
|
161
|
+
args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
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
|
|
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(argv=None):
|
|
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(argv)
|
|
76
|
+
plot(json.loads(args.results.read_text(encoding="utf-8")), args.output)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
main()
|