perfr-api 0.1.7__py3-none-win_amd64.whl

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.
perfr_api/__init__.py ADDED
@@ -0,0 +1,338 @@
1
+ # Copyright (c) 2026 The perfr Authors. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """perfr manual instrumentation for Python.
6
+
7
+ import perfr_api as perfr
8
+
9
+ perfr.init() # finds libperfr, or stays quiet
10
+ with perfr.scope("update"):
11
+ ...
12
+ perfr.value("fps", 59.9)
13
+
14
+ @perfr.scope # or @perfr.scope("a name")
15
+ def render(frame): ...
16
+
17
+ Pure Python, no dependencies, no compiled wheel. The producer -- the
18
+ shared-memory ring a running perfr drains -- is the same
19
+ ``libperfr`` that C and C++ load through ``perfr.h``, found by the same
20
+ rules and loaded with ctypes. Doing the ring in Python instead would be slower
21
+ and, on ARM, wrong: the claim is an atomic add and the commit a release store,
22
+ and Python can emit neither.
23
+
24
+ Where the library is looked for, in order:
25
+
26
+ 1. ``$PERFR_LIB``: the full path of the library file. When set it is the
27
+ only place tried, so a wrong path fails visibly.
28
+ 2. beside ``perfr``: the directory of the ``perfr`` on
29
+ ``PATH``, then ``~/.local/bin`` (the install script's default) and
30
+ ``~/.perfr/bin``. The service is the authority on the ring protocol
31
+ version, so its own library wins over any other copy.
32
+ 3. beside this package: the copy bundled in the wheel, always matched to
33
+ this package's version.
34
+ 4. the system loader.
35
+
36
+ Every call is a no-op when the library is missing or ``init()`` was not
37
+ called, the same as in C. Names may be ``str`` or ``bytes``; ``bytes`` skips
38
+ an encode on the hot path. Handles are plain ints and ``0`` means "no event".
39
+ """
40
+
41
+ import ctypes
42
+ import ctypes.util
43
+ import functools
44
+ import os
45
+ import shutil
46
+ import sys
47
+
48
+ __all__ = [
49
+ "ABI_VERSION", "DEBUG", "E_ABI", "E_NOLIB", "ERROR", "FATAL", "INFO", "TRACE", "WARN",
50
+ "available", "frame_mark", "init", "instant", "library_path", "link", "log", "now_ns", "scope",
51
+ "scope_async", "shutdown", "span", "span_async", "start", "start_async", "stop", "value",
52
+ ]
53
+ __version__ = "0.1.7"
54
+
55
+ #: The ABI this package speaks; the library hands out its table only for it.
56
+ ABI_VERSION = 1
57
+ #: ``init()`` results beyond 0 (ok) and a negative errno.
58
+ E_NOLIB = -1000
59
+ E_ABI = -1001
60
+
61
+ TRACE, DEBUG, INFO, WARN, ERROR, FATAL = range(6)
62
+
63
+ _lib = None
64
+ _lib_path = None
65
+ _lib_error = None
66
+
67
+ if sys.platform == "win32":
68
+ _LIB_FILE, _SERVICE_FILE = "libperfr.dll", "perfr.exe"
69
+ elif sys.platform == "darwin":
70
+ _LIB_FILE, _SERVICE_FILE = "libperfr.dylib", "perfr"
71
+ else:
72
+ _LIB_FILE, _SERVICE_FILE = "libperfr.so", "perfr"
73
+
74
+
75
+ def _candidates():
76
+ # The service is the authority on the ring's protocol version: it refuses a
77
+ # segment whose version is not its own, so the library that writes must
78
+ # match the service that reads. When a service is reachable, its own
79
+ # library is therefore preferred over the copy bundled in this wheel, which
80
+ # matters only when the two drift (a pinned wheel against a newer service).
81
+ # With PERFR_LIB set, that path is the only one tried, so a wrong path
82
+ # fails visibly instead of loading some other copy.
83
+ env = os.environ.get("PERFR_LIB")
84
+ if env:
85
+ yield env
86
+ return
87
+ service = shutil.which(_SERVICE_FILE)
88
+ if service:
89
+ yield os.path.join(os.path.dirname(os.path.realpath(service)), _LIB_FILE)
90
+ home = os.path.expanduser("~")
91
+ for sub in ((".perfr", "bin"),) if sys.platform == "win32" else ((".local", "bin"), (".perfr", "bin")):
92
+ yield os.path.join(home, *sub, _LIB_FILE)
93
+ # The copy shipped inside this wheel, always version-matched to the package.
94
+ yield os.path.join(os.path.dirname(os.path.abspath(__file__)), _LIB_FILE)
95
+ found = ctypes.util.find_library("perfr")
96
+ if found:
97
+ yield found
98
+ yield _LIB_FILE
99
+
100
+
101
+ def _open(path):
102
+ # PyDLL keeps the GIL across the call. The functions never block, never
103
+ # call back into Python and take about fifteen nanoseconds; dropping and
104
+ # retaking the GIL around each would cost more than the call.
105
+ lib = ctypes.PyDLL(path)
106
+ lib.perfr_api_table_v1.argtypes = (ctypes.c_uint32,)
107
+ lib.perfr_api_table_v1.restype = ctypes.c_void_p
108
+ if not lib.perfr_api_table_v1(ABI_VERSION):
109
+ raise OSError(E_ABI, "libperfr speaks another ABI")
110
+ lib.perfr_init.argtypes = ()
111
+ lib.perfr_init.restype = ctypes.c_int
112
+ lib.perfr_shutdown.argtypes = ()
113
+ lib.perfr_shutdown.restype = None
114
+ for fn in (lib.perfr_start, lib.perfr_start_async, lib.perfr_instant):
115
+ fn.argtypes = (ctypes.c_char_p, ctypes.c_size_t)
116
+ fn.restype = ctypes.c_uint64
117
+ lib.perfr_stop.argtypes = (ctypes.c_uint64,)
118
+ lib.perfr_stop.restype = None
119
+ lib.perfr_link.argtypes = (ctypes.c_uint64, ctypes.c_uint64)
120
+ lib.perfr_link.restype = None
121
+ lib.perfr_value.argtypes = (ctypes.c_char_p, ctypes.c_size_t, ctypes.c_double)
122
+ lib.perfr_value.restype = None
123
+ lib.perfr_now_ns.argtypes = ()
124
+ lib.perfr_now_ns.restype = ctypes.c_uint64
125
+ for fn in (lib.perfr_span, lib.perfr_span_async):
126
+ fn.argtypes = (ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint64, ctypes.c_uint64)
127
+ fn.restype = None
128
+ # Logging was appended. A library from before this package leaves the
129
+ # symbol absent; `log` then stays a no-op.
130
+ if hasattr(lib, "perfr_log"):
131
+ lib.perfr_log.argtypes = (ctypes.c_uint8, ctypes.c_char_p, ctypes.c_size_t)
132
+ lib.perfr_log.restype = None
133
+ # So were frame marks.
134
+ if hasattr(lib, "perfr_frame_mark"):
135
+ lib.perfr_frame_mark.argtypes = (ctypes.c_char_p, ctypes.c_size_t)
136
+ lib.perfr_frame_mark.restype = None
137
+ return lib
138
+
139
+
140
+ def _load():
141
+ global _lib, _lib_path, _lib_error
142
+ if _lib is not None or _lib_error is not None:
143
+ return _lib
144
+ for path in _candidates():
145
+ if not os.path.isabs(path) or os.path.exists(path):
146
+ try:
147
+ _lib = _open(path)
148
+ _lib_path = path
149
+ return _lib
150
+ except OSError as error:
151
+ if getattr(error, "errno", None) == E_ABI:
152
+ _lib_error = E_ABI
153
+ return None
154
+ continue
155
+ _lib_error = E_NOLIB
156
+ return None
157
+
158
+
159
+ def _name(name):
160
+ return name if isinstance(name, bytes) else name.encode("utf-8")
161
+
162
+
163
+ def init():
164
+ """Finds and loads ``libperfr``, then creates this process's segment
165
+ so a running ``perfr`` can find it. Idempotent.
166
+
167
+ Returns 0 on success, ``E_NOLIB`` or ``E_ABI`` when no usable library was
168
+ found, or a negative errno if the segment could not be created. Every
169
+ other call stays a valid no-op in each case.
170
+
171
+ A forked child (``os.fork``, ``multiprocessing`` with the fork start
172
+ method) does not inherit the segment: every call in it is a no-op until
173
+ the child calls ``init()`` itself."""
174
+ lib = _load()
175
+ return lib.perfr_init() if lib else _lib_error
176
+
177
+
178
+ def shutdown():
179
+ """Removes the segment's name. Safe to skip; the service sweeps segments
180
+ of exited processes."""
181
+ if _lib:
182
+ _lib.perfr_shutdown()
183
+
184
+
185
+ def available():
186
+ """Whether a library is loaded, i.e. ``init()`` found one."""
187
+ return _lib is not None
188
+
189
+
190
+ def library_path():
191
+ """The library ``init()`` loaded, or ``None``. For diagnostics."""
192
+ return _lib_path
193
+
194
+
195
+ def start(name):
196
+ """Begins a scope on the calling thread; returns its handle."""
197
+ b = _name(name)
198
+ return _lib.perfr_start(b, len(b)) if _lib else 0
199
+
200
+
201
+ def start_async(name):
202
+ """Begins a scope that may be stopped from any thread, on its own track."""
203
+ b = _name(name)
204
+ return _lib.perfr_start_async(b, len(b)) if _lib else 0
205
+
206
+
207
+ def stop(handle):
208
+ """Ends a scope, from any thread. ``0`` is a no-op."""
209
+ if _lib and handle:
210
+ _lib.perfr_stop(handle)
211
+
212
+
213
+ def instant(name):
214
+ """A point in time with a name and no duration; returns a handle so it
215
+ can be either end of a link."""
216
+ b = _name(name)
217
+ return _lib.perfr_instant(b, len(b)) if _lib else 0
218
+
219
+
220
+ def link(src, dst):
221
+ """An arrow from one event to another, across threads if need be."""
222
+ if _lib and src and dst:
223
+ _lib.perfr_link(src, dst)
224
+
225
+
226
+ def value(name, v):
227
+ """A value to graph over time on a track named ``name``."""
228
+ if _lib:
229
+ b = _name(name)
230
+ _lib.perfr_value(b, len(b), float(v))
231
+
232
+
233
+ def now_ns():
234
+ """``CLOCK_MONOTONIC`` nanoseconds, the clock of every timestamp; ``0``
235
+ while no library is loaded."""
236
+ return _lib.perfr_now_ns() if _lib else 0
237
+
238
+
239
+ def span(name, start_ns, end_ns):
240
+ """A complete scope at timestamps you supply (``now_ns()``'s clock)."""
241
+ if _lib:
242
+ b = _name(name)
243
+ _lib.perfr_span(b, len(b), int(start_ns), int(end_ns))
244
+
245
+
246
+ def span_async(name, start_ns, end_ns):
247
+ """A complete async span at supplied timestamps, on its own track."""
248
+ if _lib:
249
+ b = _name(name)
250
+ _lib.perfr_span_async(b, len(b), int(start_ns), int(end_ns))
251
+
252
+
253
+ class scope:
254
+ """A scope as a context manager or a decorator.
255
+
256
+ with perfr.scope("update") as s: # s.handle is the handle
257
+ ...
258
+
259
+ @perfr.scope("render") # or bare @perfr.scope: the
260
+ def render(frame): ... # function's qualified name
261
+ """
262
+
263
+ __slots__ = ("name", "handle", "_async")
264
+
265
+ def __new__(cls, name=None, async_=False):
266
+ if callable(name): # bare @scope: decorate right away
267
+ return cls(None, async_)(name)
268
+ return super().__new__(cls)
269
+
270
+ def __init__(self, name=None, async_=False):
271
+ # None, not b"": as a decorator, no name means the function's, and
272
+ # that is not known until __call__ is handed the function.
273
+ self.name = None if name is None else _name(name)
274
+ self.handle = 0
275
+ self._async = async_
276
+
277
+ def __enter__(self):
278
+ name = self.name or b""
279
+ self.handle = start_async(name) if self._async else start(name)
280
+ return self
281
+
282
+ def __exit__(self, *exc):
283
+ stop(self.handle)
284
+ return False
285
+
286
+ def __call__(self, fn):
287
+ name = self.name if self.name is not None else _name(fn.__qualname__)
288
+ starter = start_async if self._async else start
289
+
290
+ @functools.wraps(fn)
291
+ def wrapper(*args, **kwargs):
292
+ handle = starter(name)
293
+ try:
294
+ return fn(*args, **kwargs)
295
+ finally:
296
+ stop(handle)
297
+
298
+ return wrapper
299
+
300
+
301
+ def scope_async(name=None):
302
+ """``scope`` for a scope that may be stopped from any thread."""
303
+ return scope(name, async_=True)
304
+
305
+
306
+ def log(level, message):
307
+ """Records a log line. A no-op when the library is missing or nobody is
308
+ capturing. The line carries ``level`` (``TRACE`` .. ``FATAL``), the thread
309
+ and the timestamp. The viewer files it under every scope that was open on
310
+ this thread at that time, so a scope is the way to group lines:
311
+
312
+ with perfr.scope("simulation"):
313
+ perfr.log(perfr.INFO, "tick")
314
+ """
315
+ if _lib and hasattr(_lib, "perfr_log"):
316
+ b = _name(message)
317
+ _lib.perfr_log(int(level) & 0xFF, b, len(b))
318
+
319
+
320
+ def frame_mark(name=""):
321
+ """Marks a frame boundary: the frame that was running ends here and the
322
+ next one begins. Call it once per frame, at the same point of the loop
323
+ each time. The viewer draws the time between two marks as one frame, on a
324
+ ``frames`` lane under the calling thread, and a line down the timeline at
325
+ each mark.
326
+
327
+ ``name`` says which series of frames the mark belongs to, for a program
328
+ with more than one loop; leave it out for the main one. A no-op when the
329
+ library is missing or nobody is capturing.
330
+
331
+ while running:
332
+ update()
333
+ perfr.frame_mark()
334
+ """
335
+ if _lib and hasattr(_lib, "perfr_frame_mark"):
336
+ b = _name(name)
337
+ _lib.perfr_frame_mark(b, len(b))
338
+
perfr_api/libperfr.dll ADDED
Binary file
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: perfr-api
3
+ Version: 0.1.7
4
+ Summary: perfr manual instrumentation for Python: scopes, instants, links and values on a timeline a running perfr draws
5
+ Author: The perfr Authors
6
+ License-Expression: BSD-2-Clause
7
+ Project-URL: Homepage, https://github.com/perfr/perfr
8
+ Project-URL: Source, https://github.com/perfr/perfr/tree/main/crates/perfr-api/python
9
+ Keywords: profiling,tracing,instrumentation,perfr
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Software Development :: Debuggers
17
+ Classifier: Topic :: System :: Monitoring
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+
21
+ # perfr-api
22
+
23
+ perfr manual instrumentation for Python. Pure Python, no dependencies.
24
+
25
+ ```python
26
+ import perfr_api as perfr
27
+
28
+ perfr.init() # finds libperfr, or stays quiet
29
+
30
+ with perfr.scope("update"):
31
+ ...
32
+
33
+ @perfr.scope # or @perfr.scope("a name")
34
+ def render(frame):
35
+ ...
36
+
37
+ perfr.value("fps", 59.9)
38
+ perfr.instant("level loaded")
39
+ perfr.log(perfr.INFO, "tick")
40
+ perfr.frame_mark() # once per turn of the loop
41
+ ```
42
+
43
+ Run `perfr`, open its viewer, pick the Python process, press Record.
44
+
45
+ ## How it finds the library
46
+
47
+ The producer is the same `libperfr` that C and C++ load through
48
+ `perfr.h`. The package looks, in order, at `$PERFR_LIB`, beside the
49
+ `perfr` on `PATH` (then `~/.local/bin`, `~/.perfr/bin`), the copy
50
+ bundled in this wheel, then the system loader. The service comes first
51
+ because it is the authority on the ring protocol version: the library that
52
+ writes must match the service that reads, and a running service's own
53
+ library is the one guaranteed to. Without any library every call is a no-op
54
+ and `init()` returns `perfr_api.E_NOLIB`.
55
+
56
+ ## API
57
+
58
+ `init() -> int`, `shutdown()`, `available()`, `library_path()`,
59
+ `start(name) -> handle`, `start_async(name)`, `stop(handle)`,
60
+ `instant(name) -> handle`, `link(src, dst)`, `value(name, v)`,
61
+ `now_ns()`, `span(name, start_ns, end_ns)`, `span_async(...)`,
62
+ `log(level, message)` with `TRACE` .. `FATAL`, `frame_mark(name="")`,
63
+ `scope(name)` and `scope_async(name)` as context managers or decorators.
64
+
65
+ `frame_mark()` says where one frame ends and the next begins; the viewer
66
+ draws the frames as a strip of frame times and as bands behind this
67
+ process's tracks. A
68
+ name marks a series of its own, for a program with more than one loop. With
69
+ a `libperfr` from before frame marks, or before logging, that call is a
70
+ no-op and the rest work.
71
+
72
+ Names may be `str` or `bytes`; `bytes` skips an encode on the hot path.
73
+ Handles are ints; `0` means "no event" and every function accepts it.
@@ -0,0 +1,6 @@
1
+ perfr_api/__init__.py,sha256=lXnhuhEk2avDdzEe31BNZO76y8aLAG7aZHaZbOkXPG4,11784
2
+ perfr_api/libperfr.dll,sha256=p3FtXhVwG1jB9_rNCXHe9-0ms91jyLSfqwmjnKD9Aqs,254464
3
+ perfr_api-0.1.7.dist-info/METADATA,sha256=sHP_GIrGlg_yeJ_JhxKXjK_VZv2TNMY9wOMgCX4_bG4,2915
4
+ perfr_api-0.1.7.dist-info/WHEEL,sha256=bhMFZwp6VMtrbl2Ck6PlXryKaCggO1NzYn_HcFbBF1I,97
5
+ perfr_api-0.1.7.dist-info/top_level.txt,sha256=Lu1MhK_PTXIxvUeNJsxTgQ7k6TLfsiGw2l7vvYnJsYk,10
6
+ perfr_api-0.1.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1 @@
1
+ perfr_api