/**
* In-process syscall counting via `perf_event_open` tracepoints, in pure D —
* `strace -c` without a subprocess or ptrace.
*
* A counter group is opened over syscall tracepoints: `raw_syscalls:sys_enter`
* (the group leader) counts *every* syscall, and one `syscalls:sys_enter_<name>`
* counter per requested name gives the per-syscall breakdown. The tracepoint ids
* come from `tracefs` (`/sys/kernel/tracing/events/<group>/<event>/id`). Counting
* is kernel-side, so — like `perf.d` — a separate counting pass brackets each
* benchmark's timed body with `ENABLE`/`DISABLE`, and the ioctls never perturb
* the reported timings.
*
* `attr.inherit` is set, so counters clone into every thread the process spawns
* *after* `perf_event_open` — and the group opens once at bench-mode start,
* before any case's setup runs, so worker pools created in untimed setup are
* followed too (their syscalls aggregate into the leader's group read). Only
* threads that already existed when the group opened are not followed — that
* needs per-TID attach (a later refinement) or the ptrace backend the roadmap
* prepares behind the same `--syscalls` flag.
*
* Tracepoints need `perf_event_paranoid <= 1`; where they can't be opened — and
* everywhere off Linux — the group degrades to unavailable and the columns are
* simply omitted. Pure D over druntime's `core.sys.linux.perf_event`; no ImportC.
*/
module (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.syscallsIn-process syscall counting via perf_event_open tracepoints, in pure D —
strace -c without a subprocess or ptrace.
A counter group is opened over syscall tracepoints: raw_syscalls:sys_enter
(the group leader) counts every syscall, and one ``syscalls:sys_enter_<name>
counter per requested name gives the per-syscall breakdown. The tracepoint ids
come from tracefs (/sys/kernel/tracing/events/<group>/<event>/id). Counting
is kernel-side, so — like perf.d — a separate counting pass brackets each
benchmark's timed body with ENABLE/DISABLE, and the ioctls never perturb
the reported timings.
attr.inherit is set, so counters clone into every thread the process spawns
after perf_event_open — and the group opens once at bench-mode start,
before any case's setup runs, so worker pools created in untimed setup are
followed too (their syscalls aggregate into the leader's group read). Only
threads that already existed when the group opened are not followed — that
needs per-TID attach (a later refinement) or the ptrace backend the roadmap
prepares behind the same --syscalls`` flag.
Tracepoints need perf_event_paranoid <= 1; where they can't be opened — and
everywhere off Linux — the group degrades to unavailable and the columns are
simply omitted. Pure D over druntime's core.sys.linux.perf_event; no ImportC.
syscalls;
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) sparkles.profiling.counters.syscalls.text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into text (the three character widths).
text;
import (package) stdstd.(module) std.exceptionThis module defines functions related to exceptions and general error
handling. It also defines functions intended to aid in unit testing.
Category Functions Assumptions assertNotThrown assertThrown assumeUnique assumeWontThrow mayPointTo Enforce doesPointTo enforce errnoEnforce Handlers collectException collectExceptionMsg ifThrown handle Other basicExceptionCtors emptyExceptionMsg ErrnoException RangePrimitive
Source
std/exception.d
Examples
Synopis
import core.stdc.stdlib : malloc, free;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map, splitter;
import std.algorithm.searching : endsWith;
import std.conv : ConvException, to;
import std.range : front, retro;
// use enforce like assert
int a = 3;
enforce(a > 2, "a needs to be higher than 2.");
// enforce can throw a custom exception
enforce!ConvException(a > 2, "a needs to be higher than 2.");
// enforce will return it's input
enum size = 42;
auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
scope(exit) free(memory.ptr);
// collectException can be used to test for exceptions
Exception e = collectException("abc".to!int);
assert(e.file.endsWith("conv.d"));
// and just for the exception message
string msg = collectExceptionMsg("abc".to!int);
assert(msg == "Unexpected 'a' when converting from type string to type int");
// assertThrown can be used to assert that an exception is thrown
assertThrown!ConvException("abc".to!int);
// ifThrown can be used to provide a default value if an exception is thrown
assert("x".to!int().ifThrown(0) == 0);
// handle is a more advanced version of ifThrown for ranges
auto r = "12,1337z32,54".splitter(',').map!(a => to!int(a));
auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0);
assert(h.equal([12, 0, 54]));
assertThrown!ConvException(h.retro.equal([54, 0, 12]));
// basicExceptionCtors avoids the boilerplate when creating custom exceptions
static class MeaCulpa : Exception
{
mixin basicExceptionCtors;
}
e = collectException((){throw new MeaCulpa("diagnostic message");}());
assert(e.msg == "diagnostic message");
assert(e.file == __FILE__);
assert(e.line == __LINE__ - 3);
// assumeWontThrow can be used to cast throwing code into `nothrow`
void exceptionFreeCode() nothrow
{
// auto-decoding only throws if an invalid UTF char is given
assumeWontThrow("abc".front);
}
// assumeUnique can be used to cast mutable instance to an `immutable` one
// use with care
char[] str = " mutable".dup;
str[0 .. 2] = "im";
immutable res = assumeUnique(str);
assert(res == "immutable");
exception : (alias template) sparkles.profiling.counters.syscalls.assumeWontThrow = std.exception.assumeWontThrow(T)(lazy T expr, string msg = null, string file = __FILE__, size_t line = __LINE__)Wraps a possibly-throwing expression in a nothrow wrapper so that it
can be called by a nothrow function.
This wrapper function documents commitment on the part of the caller that
the appropriate steps have been taken to avoid whatever conditions may
trigger an exception during the evaluation of expr. If it turns out
that the expression does throw at runtime, the wrapper will throw an
AssertError.
(Note that Throwable objects such as AssertError that do not
subclass Exception may be thrown even from nothrow functions,
since they are considered to be serious runtime problems that cannot be
recovered from.)
assumeWontThrow;
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.capabilityThe capability seam: what can this host measure, as a first-class value.
Every acquisition backend advertises a CapabilityReport after its open
handshake — one Capability flag per survey concern, with a reasoned
CapabilityAbsence entry for everything it cannot deliver on this host,
this run. Capability is a runtime probe result, never a compile-time
assumption: the same binary reports differently under a hardened
perf_event_paranoid, a root-only tracefs, or a PMU-less container.
isCounterBackend names the instance contract CounterGroups has always
demanded of a tier (available/status/capabilities/close/count);
optional primitives (hasSnapshot, hasNamedColumns) unlock optional
behavior by presence, per the DbI guidelines. Construction is deliberately
outside the trait — tryOpen arity varies per tier (perf: bool;
syscalls: bool + names) and stays a per-tier concern of
CounterGroups.open.
The evidence base is the CPU-PMU research catalog
(docs/research/cpu-pmu/backend-proposal.md §2); the shipped shapes
deviate from its sketch where the real surface demanded it (see
docs/specs/test-runner/SPEC.md §6.2).
capability : (enum) sparkles.profiling.counters.capability.CapabilityOne flag per survey concern (plus real-world sub-splits). Advertised per
backend instance after its open handshake.
Capability, (struct) sparkles.profiling.counters.capability.CapabilityAbsenceOne absent capability with its host-grounded reason.
CapabilityAbsence,
(struct) sparkles.profiling.counters.capability.CapabilityReportWhat a backend can deliver on this host, this run: the present flags OR-ed
together, and a reasoned entry per absent flag (in allCapabilities
order). A flag mentioned in neither is outside the backend's domain.
CapabilityReport, (alias) sparkles.profiling.counters.syscalls.has = bool sparkles.profiling.counters.capability.has(in sparkles.profiling.counters.capability.CapabilityReport r, sparkles.profiling.counters.capability.Capability flag) pure nothrow @nogc @safeWhether flag is advertised present.
has, (alias template) sparkles.profiling.counters.syscalls.hasNamedColumns = sparkles.profiling.counters.capability.hasNamedColumns(B)Optional
dynamic per-column names parallel to a row's counts (the
syscall tier's named tracepoints).
hasNamedColumns, (alias template) sparkles.profiling.counters.syscalls.hasSnapshot = sparkles.profiling.counters.capability.hasSnapshot(B)Optional
a cheap cumulative snapshot (the snapshot/delta source shape —
tier-0 today, the workload window model tomorrow). Presence, not
declaration, unlocks it.
hasSnapshot, (alias template) sparkles.profiling.counters.syscalls.isCounterBackend = sparkles.profiling.counters.capability.isCounterBackend(B)The required backend surface — CounterGroups' implicit per-tier contract
made nameable: const-callable probe observers (available, status,
capabilities), resource release, and the bracketed counting pass
returning that backend's row-stats value. The return type of count is
deliberately unconstrained (it differs per tier), as are attributes
(count is a template with inferred attributes).
isCounterBackend,
(alias) sparkles.profiling.counters.syscalls.probeParanoid = sparkles.profiling.counters.capability.ProbedValue sparkles.profiling.counters.capability.probeParanoid() nothrow @nogc @safeThe kernel's perf_event_paranoid level (-1 … 4); ok false when
unreadable.
probeParanoid, (alias) sparkles.profiling.counters.syscalls.reasonFor = string sparkles.profiling.counters.capability.reasonFor(in sparkles.profiling.counters.capability.CapabilityReport r, sparkles.profiling.counters.capability.Capability flag) pure nothrow @nogc @safeThe reason flag is absent; null when present or outside the report's
domain. (Returning the second-level slice out of an in report is legal
under dip1000 — scope is non-transitive; a helper returning the
first-level absences slice itself would not compile.)
reasonFor;
/// Per-iteration syscall counts of one counting pass. `total` is every syscall
/// (`raw_syscalls:sys_enter`); `counts[i]` is the per-iteration count of the
/// tracepoint named `named[i]` (`nan` if that tracepoint could not be opened).
struct (struct) sparkles.profiling.counters.syscalls.SyscallStatsPer-iteration syscall counts of one counting pass. total is every syscall
(raw_syscalls:sys_enter); counts[i] is the per-iteration count of the
tracepoint named named[i] (nan if that tracepoint could not be opened).
SyscallStats
{
ulong (field) ulong sparkles.profiling.counters.syscalls.SyscallStats.itersiters;
double (field) double sparkles.profiling.counters.syscalls.SyscallStats.totaltotal = 0;
const((alias) object.string = stringstring)[] (field) const(string)[] sparkles.profiling.counters.syscalls.SyscallStats.namednamed;
double[] (field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts;
double (field) double sparkles.profiling.counters.syscalls.SyscallStats.scalescale = 1;
}
/// Parses the single integer in a tracepoint `id` file (`"1234\n"`); `-1` on
/// empty/garbage.
long long sparkles.profiling.counters.syscalls.parseTracepointId(const(char)[] content) pure nothrow @nogc @safeParses the single integer in a tracepoint id file ("1234\n"); -1 on
empty/garbage.
parseTracepointId(const(char)[] (parameter) const(char)[] contentcontent) @safe pure nothrow @nogc
{
(alias) object.size_t = ulongsize_t (local variable) ulong ii = 0;
while ((local variable) ulong ii < (parameter) const(char)[] contentcontent.(field) ulong const(char)[].lengthlength && ((parameter) const(char)[] contentcontent[(local variable) ulong ii] == ' ' || (parameter) const(char)[] contentcontent[(local variable) ulong ii] == '\t'))
(local variable) ulong ii++;
long (local variable) long valuevalue = 0;
bool (local variable) bool anyany;
while ((local variable) ulong ii < (parameter) const(char)[] contentcontent.(field) ulong const(char)[].lengthlength && (parameter) const(char)[] contentcontent[(local variable) ulong ii] >= '0' && (parameter) const(char)[] contentcontent[(local variable) ulong ii] <= '9')
{
(local variable) long valuevalue = (local variable) long valuevalue * 10 + ((parameter) const(char)[] contentcontent[(local variable) ulong ii] - '0');
(local variable) ulong ii++;
(local variable) bool anyany = true;
}
return (local variable) bool anyany ? (local variable) long valuevalue : -1;
}
version (linuxlinux)
{
import (package) corecore.(package) core.syssys.(package) core.sys.linuxlinux.(module) core.sys.linux.perf_eventD header file for perf_event_open system call.
Converted from linux userspace header, comments included.
perf_event : (struct) core.sys.linux.perf_event.perf_event_attrHardware event_id to monitor via a performance monitoring event:
@sample_max_stack: Max number of frame pointers in a callchain,
should be < /proc/sys/kernel/perf_event_max_stack
perf_event_attr, (alias) sparkles.profiling.counters.syscalls.perf_event_open = long core.sys.linux.perf_event.perf_event_open(core.sys.linux.perf_event.perf_event_attr* hw_event, int pid, int cpu, int group_fd, ulong flags) nothrow @nogcperf_event_open,
(enum) core.sys.linux.perf_event.perf_type_idattr.type
perf_type_id, (enum) core.sys.linux.perf_event.perf_event_read_formatThe format of the data returned by read() on a perf event fd,
as specified by attr.read_format:
struct read_format {
{ u64 value;
{ u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED
{ u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING
{ u64 id; } && PERF_FORMAT_ID
} && !PERF_FORMAT_GROUP
{ u64 nr;
{ u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED
{ u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING
{ u64 value;
{ u64 id; } && PERF_FORMAT_ID
} cntr[nr];
} && PERF_FORMAT_GROUP
};
perf_event_read_format,
(alias constant) sparkles.profiling.counters.syscalls.PERF_EVENT_IOC_DISABLE = int core.sys.linux.perf_event.PERF_EVENT_IOC_DISABLE = 9217PERF_EVENT_IOC_DISABLE, (alias constant) sparkles.profiling.counters.syscalls.PERF_EVENT_IOC_ENABLE = int core.sys.linux.perf_event.PERF_EVENT_IOC_ENABLE = 9216Ioctls that can be done on a perf event fd:
PERF_EVENT_IOC_ENABLE;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.unistdD header file for POSIX.
unistd : (alias) sparkles.profiling.counters.syscalls.posixClose = int core.sys.posix.unistd.close(int) nothrow @nogc @trustedposixClose = (alias) sparkles.profiling.counters.syscalls.posixClose = int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose;
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (struct) sparkles.profiling.counters.perf_group.GroupSnapshotOne cumulative PERF_FORMAT_GROUP reading at a window edge — a pure
read(2), no ioctl, no RESET — so an outer window candidate and
inner in-body windows can overlap freely: each computes its own deltas
between its own two edges.
GroupSnapshot;
private enum (constant) int sparkles.profiling.counters.syscalls.maxNamed = 62group read buffer is double[1 + maxNamed]
maxNamed = 62; /// group read buffer is `double[1 + maxNamed]`
/// Reads a tracepoint's numeric id from `tracefs`; `-1` if unavailable.
long long sparkles.profiling.counters.syscalls.tracepointId(string group, string event) @safeReads a tracepoint's numeric id from tracefs; -1 if unavailable.
tracepointId((alias) object.string = stringstring (parameter) string groupgroup, (alias) object.string = stringstring (parameter) string eventevent) @safe
{
static long long sparkles.profiling.counters.syscalls.tracepointId.readId(string path) nothrow @safereadId((alias) object.string = stringstring (parameter) string pathpath) @safe
{
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.fcntlD header file for POSIX.
fcntl : open, (alias constant) O_RDONLY = int core.sys.posix.fcntl.O_RDONLY = 0O_RDONLY;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.unistdD header file for POSIX.
unistd : (alias) read = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread, (alias) close = int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose;
const (local variable) const(string) cPathcPath = (parameter) string pathpath ~ "\0";
const (local variable) const(int) fdfd = (() @trusted => open(int core.sys.posix.fcntl.open64(scope const(char*), int, ...) nothrow @nogccPath.(field) immutable(char)* const(string).ptrptr, (constant) int core.sys.posix.fcntl.O_RDONLY = 0O_RDONLY))();
if ((local variable) const(int) fdfd < 0)
return -1;
scope (exit)
(() @trusted => int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose((local variable) const(int) fdfd))();
char[32] (local variable) char[32] bufbuf;
const (local variable) const(long) nn = (() @trusted => long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread((local variable) const(int) fdfd, (local variable) char[32] bufbuf.(constant) char* char[32].ptr = &bufptr, (local variable) char[32] bufbuf.(constant) ulong char[32].length = 32LUlength))();
return (local variable) const(long) nn > 0 ? long sparkles.profiling.counters.syscalls.parseTracepointId(const(char)[] content) pure nothrow @nogc @safeParses the single integer in a tracepoint id file ("1234\n"); -1 on
empty/garbage.
parseTracepointId((local variable) char[32] bufbuf[0 .. (local variable) const(long) nn]) : -1;
}
const (local variable) const(string) suffixsuffix = "events/" ~ (parameter) string groupgroup ~ "/" ~ (parameter) string eventevent ~ "/id";
const (local variable) const(long) idid = long sparkles.profiling.counters.syscalls.tracepointId.readId(string path) nothrow @safereadId("/sys/kernel/tracing/" ~ (local variable) const(string) suffixsuffix);
return (local variable) const(long) idid >= 0 ? (local variable) const(long) idid : long sparkles.profiling.counters.syscalls.tracepointId.readId(string path) nothrow @safereadId("/sys/kernel/debug/tracing/" ~ (local variable) const(string) suffixsuffix);
}
/// The syscall tracepoint counter group (Linux). `tryOpen` once; `count`
/// brackets one benchmark's timed body per iteration.
struct (struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup
{
private int[] (field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds; /// [leader(total), named...]; -1 = unavailable
private const((alias) object.string = stringstring)[] (field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_;
private int (field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen;
private bool (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.requestedrequested;
private bool (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.idUnreadabletracefs id files could not be read
idUnreadable; /// tracefs id files could not be read
private bool (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened;
/// Whether syscall counters are usable on this machine.
bool bool sparkles.profiling.counters.syscalls.SyscallGroup.available() const pure nothrow @nogc @safeWhether syscall counters are usable on this machine.
available() const @safe pure nothrow @nogc => (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened;
/// The requested per-syscall names (parallel to a row's `counts`).
const((alias) object.string = stringstring)[] const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names() const pure nothrow @nogc @safeThe requested per-syscall names (parallel to a row's counts).
names() const @safe pure nothrow @nogc => (field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_;
/// Human-readable availability, for a report header.
(alias) object.string = stringstring string sparkles.profiling.counters.syscalls.SyscallGroup.status() const pure nothrow @safeHuman-readable availability, for a report header.
status() const @safe pure nothrow
=> (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened
? "raw_syscalls:sys_enter + per-syscall tracepoints"
: "unavailable (needs readable tracefs and perf_event_paranoid ≤ 1 — usually root)";
/// The bare reason event tracing is unavailable, distinguishing the
/// independent gates: tracefs readability vs `perf_event_paranoid` —
/// and not blaming a paranoid level that is in fact permissive.
private (alias) object.string = stringstring string sparkles.profiling.counters.syscalls.SyscallGroup.tracingAbsence() const nothrow @safeThe bare reason event tracing is unavailable, distinguishing the
independent gates: tracefs readability vs perf_event_paranoid —
and not blaming a paranoid level that is in fact permissive.
tracingAbsence() const @safe nothrow
{
if (!(field) bool sparkles.profiling.counters.syscalls.SyscallGroup.requestedrequested)
return "not requested";
if ((field) bool sparkles.profiling.counters.syscalls.SyscallGroup.idUnreadabletracefs id files could not be read
idUnreadable)
return "tracefs event ids unreadable — usually root";
const (local variable) const(sparkles.profiling.counters.capability.ProbedValue) pp = sparkles.profiling.counters.capability.ProbedValue sparkles.profiling.counters.capability.probeParanoid() nothrow @nogc @safeThe kernel's perf_event_paranoid level (-1 … 4); ok false when
unreadable.
probeParanoid();
if (!(local variable) const(sparkles.profiling.counters.capability.ProbedValue) pp.(field) bool sparkles.profiling.counters.capability.ProbedValue.okok)
return "perf_event_open refused tracepoints — perf_event_paranoid? (needs ≤ 1)";
if ((local variable) const(sparkles.profiling.counters.capability.ProbedValue) pp.(field) long sparkles.profiling.counters.capability.ProbedValue.valuevalue > 1)
return string std.exception.assumeWontThrow!string(lazy string expr, string msg = null, string file = __FILE__, ulong line = cast(ulong)__LINE__) pure nothrow @safeWraps a possibly-throwing expression in a nothrow wrapper so that it
can be called by a nothrow function.
This wrapper function documents commitment on the part of the caller that
the appropriate steps have been taken to avoid whatever conditions may
trigger an exception during the evaluation of expr. If it turns out
that the expression does throw at runtime, the wrapper will throw an
AssertError.
(Note that Throwable objects such as AssertError that do not
subclass Exception may be thrown even from nothrow functions,
since they are considered to be serious runtime problems that cannot be
recovered from.)
Examples
import std.math.algebraic : sqrt;
// This function may throw.
int squareRoot(int x)
{
if (x < 0)
throw new Exception("Tried to take root of negative number");
return cast(int) sqrt(cast(double) x);
}
// This function never throws.
int computeLength(int x, int y) nothrow
{
// Since x*x + y*y is always positive, we can safely assume squareRoot
// won't throw, and use it to implement this nothrow function. If it
// does throw (e.g., if x*x + y*y overflows a 32-bit value), then the
// program will terminate.
return assumeWontThrow(squareRoot(x*x + y*y));
}
assert(computeLength(3, 4) == 5);
assumeWontThrow(string std.conv.text!(core.interpolation.InterpolationHeader, core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints \xe2\x80\x94 perf_event_paranoid=", core.interpolation.InterpolatedExpression!"p.value", const(long), core.interpolation.InterpolatedLiteral!" (needs \xe2\x89\xa4 1)", core.interpolation.InterpolationFooter)(core.interpolation.InterpolationHeader __param_0, core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints \xe2\x80\x94 perf_event_paranoid=" __param_1, core.interpolation.InterpolatedExpression!"p.value" __param_2, const(long) __param_3, core.interpolation.InterpolatedLiteral!" (needs \xe2\x89\xa4 1)" __param_4, core.interpolation.InterpolationFooter __param_5) pure @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text((template instance) core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints \xe2\x80\x94 perf_event_paranoid="i"perf_event_open refused tracepoints — perf_event_paranoid=$(p.value) (needs ≤ 1)"));
return string std.exception.assumeWontThrow!string(lazy string expr, string msg = null, string file = __FILE__, ulong line = cast(ulong)__LINE__) pure nothrow @safeWraps a possibly-throwing expression in a nothrow wrapper so that it
can be called by a nothrow function.
This wrapper function documents commitment on the part of the caller that
the appropriate steps have been taken to avoid whatever conditions may
trigger an exception during the evaluation of expr. If it turns out
that the expression does throw at runtime, the wrapper will throw an
AssertError.
(Note that Throwable objects such as AssertError that do not
subclass Exception may be thrown even from nothrow functions,
since they are considered to be serious runtime problems that cannot be
recovered from.)
Examples
import std.math.algebraic : sqrt;
// This function may throw.
int squareRoot(int x)
{
if (x < 0)
throw new Exception("Tried to take root of negative number");
return cast(int) sqrt(cast(double) x);
}
// This function never throws.
int computeLength(int x, int y) nothrow
{
// Since x*x + y*y is always positive, we can safely assume squareRoot
// won't throw, and use it to implement this nothrow function. If it
// does throw (e.g., if x*x + y*y overflows a 32-bit value), then the
// program will terminate.
return assumeWontThrow(squareRoot(x*x + y*y));
}
assert(computeLength(3, 4) == 5);
assumeWontThrow(string std.conv.text!(core.interpolation.InterpolationHeader, core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints (seccomp or kernel policy \xe2\x80\x94 perf_event_paranoid=", core.interpolation.InterpolatedExpression!"p.value", const(long), core.interpolation.InterpolatedLiteral!" is permissive)", core.interpolation.InterpolationFooter)(core.interpolation.InterpolationHeader __param_0, core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints (seccomp or kernel policy \xe2\x80\x94 perf_event_paranoid=" __param_1, core.interpolation.InterpolatedExpression!"p.value" __param_2, const(long) __param_3, core.interpolation.InterpolatedLiteral!" is permissive)" __param_4, core.interpolation.InterpolationFooter __param_5) pure @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text((template instance) core.interpolation.InterpolatedLiteral!"perf_event_open refused tracepoints (seccomp or kernel policy \xe2\x80\x94 perf_event_paranoid="i"perf_event_open refused tracepoints (seccomp or kernel policy — perf_event_paranoid=$(p.value) is permissive)"));
}
/// What this backend can deliver: OS-event gating via tracepoints.
(struct) sparkles.profiling.counters.capability.CapabilityReportWhat a backend can deliver on this host, this run: the present flags OR-ed
together, and a reasoned entry per absent flag (in allCapabilities
order). A flag mentioned in neither is outside the backend's domain.
CapabilityReport sparkles.profiling.counters.capability.CapabilityReport sparkles.profiling.counters.syscalls.SyscallGroup.capabilities() const nothrow @safeWhat this backend can deliver: OS-event gating via tracepoints.
capabilities() const @safe nothrow
{
if ((field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened)
return (struct) sparkles.profiling.counters.capability.CapabilityReportWhat a backend can deliver on this host, this run: the present flags OR-ed
together, and a reasoned entry per absent flag (in allCapabilities
order). A flag mentioned in neither is outside the backend's domain.
CapabilityReport((enum) sparkles.profiling.counters.capability.CapabilityOne flag per survey concern (plus real-world sub-splits). Advertised per
backend instance after its open handshake.
Capability.(enum value) sparkles.profiling.counters.capability.Capability.eventTracing = 128uconcern 5: OS-event gating (tracepoints/ETW)
eventTracing, null);
return (struct) sparkles.profiling.counters.capability.CapabilityReportWhat a backend can deliver on this host, this run: the present flags OR-ed
together, and a reasoned entry per absent flag (in allCapabilities
order). A flag mentioned in neither is outside the backend's domain.
CapabilityReport((enum) sparkles.profiling.counters.capability.CapabilityOne flag per survey concern (plus real-world sub-splits). Advertised per
backend instance after its open handshake.
Capability.(enum value) sparkles.profiling.counters.capability.Capability.none = 0unone,
[(struct) sparkles.profiling.counters.capability.CapabilityAbsenceOne absent capability with its host-grounded reason.
CapabilityAbsence((enum) sparkles.profiling.counters.capability.CapabilityOne flag per survey concern (plus real-world sub-splits). Advertised per
backend instance after its open handshake.
Capability.(enum value) sparkles.profiling.counters.capability.Capability.eventTracing = 128uconcern 5: OS-event gating (tracepoints/ETW)
eventTracing, string sparkles.profiling.counters.syscalls.SyscallGroup.tracingAbsence() const nothrow @safeThe bare reason event tracing is unavailable, distinguishing the
independent gates: tracefs readability vs perf_event_paranoid —
and not blaming a paranoid level that is in fact permissive.
tracingAbsence())]);
}
/// Opens the group unless disabled: the `raw_syscalls:sys_enter` leader
/// plus one `syscalls:sys_enter_<name>` counter per requested name. A
/// name whose tracepoint can't be resolved gets a `-1` fd (its column
/// reads `nan`). Failure to open the leader leaves the group unavailable.
static (struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup sparkles.profiling.counters.syscalls.SyscallGroup sparkles.profiling.counters.syscalls.SyscallGroup.tryOpen(bool enabled, const(string)[] named) @safeOpens the group unless disabled: the raw_syscalls:sys_enter leader
plus one syscalls:sys_enter_<name> counter per requested name. A
name whose tracepoint can't be resolved gets a -1 fd (its column
reads nan). Failure to open the leader leaves the group unavailable.
tryOpen(bool (parameter) bool enabledenabled, const((alias) object.string = stringstring)[] (parameter) const(string)[] namednamed) @safe
{
(struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg;
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) bool sparkles.profiling.counters.syscalls.SyscallGroup.requestedrequested = (parameter) bool enabledenabled;
if (!(parameter) bool enabledenabled)
return (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg;
if ((parameter) const(string)[] namednamed.(field) ulong const(string)[].lengthlength > (constant) int sparkles.profiling.counters.syscalls.maxNamed = 62group read buffer is double[1 + maxNamed]
maxNamed)
(parameter) const(string)[] namednamed = (parameter) const(string)[] namednamed[0 .. (constant) int sparkles.profiling.counters.syscalls.maxNamed = 62group read buffer is double[1 + maxNamed]
maxNamed];
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_ = (parameter) const(string)[] namednamed;
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds = new int[](1 + (parameter) const(string)[] namednamed.(field) ulong const(string)[].lengthlength);
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[] = -1;
const (local variable) const(long) leaderIdleaderId = long sparkles.profiling.counters.syscalls.tracepointId(string group, string event) @safeReads a tracepoint's numeric id from tracefs; -1 if unavailable.
tracepointId("raw_syscalls", "sys_enter");
if ((local variable) const(long) leaderIdleaderId < 0)
{
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) bool sparkles.profiling.counters.syscalls.SyscallGroup.idUnreadabletracefs id files could not be read
idUnreadable = true;
return (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg;
}
const (local variable) const(int) leaderleader = (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.int sparkles.profiling.counters.syscalls.SyscallGroup.openCounter(long id, int leader) @safeOpens one tracepoint counter; group_fd is -1 for the leader.
openCounter((local variable) const(long) leaderIdleaderId, -1);
if ((local variable) const(int) leaderleader < 0)
return (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg;
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0] = (local variable) const(int) leaderleader;
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen = 1;
foreach ((parameter) ulong ii, (parameter) const(string) namename; (parameter) const(string)[] namednamed)
{
const (local variable) const(long) idid = long sparkles.profiling.counters.syscalls.tracepointId(string group, string event) @safeReads a tracepoint's numeric id from tracefs; -1 if unavailable.
tracepointId("syscalls", "sys_enter_" ~ (local variable) const(string) namename);
if ((local variable) const(long) idid < 0)
continue;
const (local variable) const(int) fdfd = (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.int sparkles.profiling.counters.syscalls.SyscallGroup.openCounter(long id, int leader) @safeOpens one tracepoint counter; group_fd is -1 for the leader.
openCounter((local variable) const(long) idid, (local variable) const(int) leaderleader);
if ((local variable) const(int) fdfd >= 0)
{
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[1 + (local variable) ulong ii] = (local variable) const(int) fdfd;
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen++;
}
}
(local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg.(field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened = true;
return (local variable) sparkles.profiling.counters.syscalls.SyscallGroup gg;
}
/// Opens one tracepoint counter; `group_fd` is `-1` for the leader.
private int int sparkles.profiling.counters.syscalls.SyscallGroup.openCounter(long id, int leader) @safeOpens one tracepoint counter; group_fd is -1 for the leader.
openCounter(long (parameter) long idid, int (parameter) int leaderleader) @safe
{
(struct) core.sys.linux.perf_event.perf_event_attrHardware event_id to monitor via a performance monitoring event:
@sample_max_stack: Max number of frame pointers in a callchain,
should be < /proc/sys/kernel/perf_event_max_stack
perf_event_attr (local variable) core.sys.linux.perf_event.perf_event_attr attrattr;
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.(field) uint core.sys.linux.perf_event.perf_event_attr.sizeSize of the attr structure, for fwd/bwd compat.
size = (struct) core.sys.linux.perf_event.perf_event_attrHardware event_id to monitor via a performance monitoring event:
@sample_max_stack: Max number of frame pointers in a callchain,
should be < /proc/sys/kernel/perf_event_max_stack
perf_event_attr.(constant) ulong core.sys.linux.perf_event.perf_event_attr.sizeof = 112LUsizeof;
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.(field) uint core.sys.linux.perf_event.perf_event_attr.typeMajor type: hardware/software/tracepoint/etc.
type = (enum) core.sys.linux.perf_event.perf_type_idattr.type
perf_type_id.(enum value) core.sys.linux.perf_event.perf_type_id.PERF_TYPE_TRACEPOINT = 2PERF_TYPE_TRACEPOINT;
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.(field) ulong core.sys.linux.perf_event.perf_event_attr.configType specific configuration information.
config = cast(ulong) (parameter) long idid;
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.void core.sys.linux.perf_event.perf_event_attr.disabled(ulong v) pure nothrow @nogc @property @safedisabled = (parameter) int leaderleader < 0;
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.void core.sys.linux.perf_event.perf_event_attr.inherit(ulong v) pure nothrow @nogc @property @safeinherit = 1; // follow threads spawned during the timed body
if ((parameter) int leaderleader < 0)
with ((enum) core.sys.linux.perf_event.perf_event_read_formatThe format of the data returned by read() on a perf event fd,
as specified by attr.read_format:
struct read_format {
{ u64 value;
{ u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED
{ u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING
{ u64 id; } && PERF_FORMAT_ID
} && !PERF_FORMAT_GROUP
{ u64 nr;
{ u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED
{ u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING
{ u64 value;
{ u64 id; } && PERF_FORMAT_ID
} cntr[nr];
} && PERF_FORMAT_GROUP
};
perf_event_read_format)
(local variable) core.sys.linux.perf_event.perf_event_attr attrattr.(field) ulong core.sys.linux.perf_event.perf_event_attr.read_formatread_format = (enum value) core.sys.linux.perf_event.perf_event_read_format.PERF_FORMAT_GROUP = 8uPERF_FORMAT_GROUP
| (enum value) core.sys.linux.perf_event.perf_event_read_format.PERF_FORMAT_TOTAL_TIME_ENABLED = 1uPERF_FORMAT_TOTAL_TIME_ENABLED
| (enum value) core.sys.linux.perf_event.perf_event_read_format.PERF_FORMAT_TOTAL_TIME_RUNNING = 2uPERF_FORMAT_TOTAL_TIME_RUNNING;
return (() @trusted => cast(int) long core.sys.linux.perf_event.perf_event_open(core.sys.linux.perf_event.perf_event_attr* hw_event, int pid, int cpu, int group_fd, ulong flags) nothrow @nogcperf_event_open(
hw_event: &(local variable) core.sys.linux.perf_event.perf_event_attr attrattr, pid: 0, cpu: -1, group_fd: (parameter) int leaderleader, flags: 0UL))();
}
private void void sparkles.profiling.counters.syscalls.SyscallGroup.closeFds() @safecloseFds() @safe
{
foreach (ref (parameter) int fdfd; (field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds)
{
if ((local variable) int fdfd >= 0)
(() @trusted => int core.sys.posix.unistd.close(int) nothrow @nogc @trustedposixClose((local variable) int fdfd))();
(local variable) int fdfd = -1;
}
(field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen = 0;
}
/// Releases the counter fds.
void void sparkles.profiling.counters.syscalls.SyscallGroup.close() @safeReleases the counter fds.
close() @safe
{
if ((field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened)
{
void sparkles.profiling.counters.syscalls.SyscallGroup.closeFds() @safecloseFds();
(field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened = false;
}
}
/// The counting pass: brackets each `timed()` with `ENABLE`/`DISABLE` so
/// `between()` runs uncounted, then reads the group. Returns per-iteration
/// counts; the `named` tracepoints are exact.
(struct) sparkles.profiling.counters.syscalls.SyscallStatsPer-iteration syscall counts of one counting pass. total is every syscall
(raw_syscalls:sys_enter); counts[i] is the per-iteration count of the
tracepoint named named[i] (nan if that tracepoint could not be opened).
SyscallStats sparkles.profiling.counters.syscalls.SyscallStats sparkles.profiling.counters.syscalls.SyscallGroup.count!(void function() pure nothrow @nogc @safe, void function() pure nothrow @nogc @safe)(scope void function() pure nothrow @nogc @safe timed, scope void function() pure nothrow @nogc @safe between, uint iters, uint batch = 1u) @safeThe counting pass: brackets each timed`()` with `ENABLE`/`DISABLE` so
between() runs uncounted, then reads the group. Returns per-iteration
counts; the named tracepoints are exact.
count(Timed, Between)(scope (alias) Timed = void function() pure nothrow @nogc @safeTimed (parameter) void function() pure nothrow @nogc @safe timedtimed, scope (alias) Between = void function() pure nothrow @nogc @safeBetween (parameter) void function() pure nothrow @nogc @safe betweenbetween,
uint (parameter) uint itersiters, uint (parameter) uint batchbatch = 1)
in ((parameter) uint itersiters > 0)
{
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (alias template) bracketCountingPass = sparkles.profiling.counters.perf_group.bracketCountingPass(Timed, Between)(int leaderFd, scope Timed timed, scope Between between, uint iters, uint batch = 1)The counting pass's ioctl bracket: RESET once, then per batch
ENABLE, batch×timed(), DISABLE, batch×between() — so only
timed() is counted and between() (a benchmark's result release) runs
uncounted. Returns the pass's time baseline for readScaledGroup.
`batch` exists because the bracket is not free: an ENABLE/DISABLE ioctl
pair costs ~2.2 µs (~3 300 retired instructions) on the Zen 4 dev box, so a
one-iteration bracket around a nanosecond-scale body reports the apparatus
rather than the body. Bracketing `batch` iterations together amortizes that
cost by `batch` while leaving the divisor (`iters`) untouched, because the
total number of `timed()` calls is exactly `iters` either way.
`batch > 1` reorders `between()` to *after* its batch's `timed()` calls, so
it is only sound when `between` is a no-op — i.e. the batched rows (a
whole body or a `BenchTiming.batched` case), which is precisely the regime
where the floor bites. Per-call `benchCase` rows keep `batch == 1`, where
this is byte-for-byte the original per-iteration bracket.
bracketCountingPass, (alias) readScaledGroup = bool sparkles.profiling.counters.perf_group.readScaledGroup(int leaderFd, uint nOpen, uint iters, ref double scale, scope double[] values, sparkles.profiling.counters.perf_group.GroupTimeBase base = GroupTimeBase(0LU, 0LU)) @safeReads a PERF_FORMAT_GROUP group from leaderFd (nOpen counters opened,
values returned in fd order). On success fills values[0 .. nOpen] with the
per-iteration averages, multiplex-corrected by the pass's enabled/running
deltas against base (see GroupTimeBase), sets scale to
round3(runningΔ/enabledΔ) (1 = no multiplexing), and returns true.
On a short/interrupted read returns false and leaves values/scale
untouched (the caller fills nan); on a pass the PMU never scheduled
(groupNeverRan) returns false with scale = 0 — the zero counts
are the kernel's <not counted> state, not measurements.
readScaledGroup;
const (local variable) const(sparkles.profiling.counters.perf_group.GroupTimeBase) basebase = sparkles.profiling.counters.perf_group.GroupTimeBase sparkles.profiling.counters.perf_group.bracketCountingPass!(void function() pure nothrow @nogc @safe, void function() pure nothrow @nogc @safe)(int leaderFd, scope void function() pure nothrow @nogc @safe timed, scope void function() pure nothrow @nogc @safe between, uint iters, uint batch = 1u) @safeThe counting pass's ioctl bracket: RESET once, then per batch
ENABLE, batch×timed`()`, `DISABLE`, batch×between() — so only
timed`()` is counted and between() (a benchmark's result release) runs
uncounted. Returns the pass's time baseline for readScaledGroup.
batch exists because the bracket is not free: an ENABLE/DISABLE ioctl
pair costs ~2.2 µs (~3 300 retired instructions) on the Zen 4 dev box, so a
one-iteration bracket around a nanosecond-scale body reports the apparatus
rather than the body. Bracketing batch iterations together amortizes that
cost by batch while leaving the divisor (iters) untouched, because the
total number of timed`()` calls is exactly iters`` either way.
batch` > 1` reorders between() to after its batch's timed`()` calls, so
it is only sound when between is a no-op — i.e. the batched rows (a
whole body or a `BenchTiming.batched` case), which is precisely the regime
where the floor bites. Per-call `benchCase` rows keep batch == 1, where
this is byte-for-byte the original per-iteration bracket.
bracketCountingPass((field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0], (parameter) void function() pure nothrow @nogc @safe timedtimed, (parameter) void function() pure nothrow @nogc @safe betweenbetween, (parameter) uint itersiters, (parameter) uint batchbatch);
(struct) sparkles.profiling.counters.syscalls.SyscallStatsPer-iteration syscall counts of one counting pass. total is every syscall
(raw_syscalls:sys_enter); counts[i] is the per-iteration count of the
tracepoint named named[i] (nan if that tracepoint could not be opened).
SyscallStats (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) ulong sparkles.profiling.counters.syscalls.SyscallStats.itersiters = (parameter) uint itersiters;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) const(string)[] sparkles.profiling.counters.syscalls.SyscallStats.namednamed = (field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts = new double[]((field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_.(field) ulong const(string)[].lengthlength);
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts[] = double.(constant) double double.nan = nannan;
// One scaled per-iteration value per opened counter, in fds order; a
// short read → total unavailable (named counts stay nan).
double[1 + (constant) int sparkles.profiling.counters.syscalls.maxNamed = 62group read buffer is double[1 + maxNamed]
maxNamed] (local variable) double[63] valuesvalues;
if (!bool sparkles.profiling.counters.perf_group.readScaledGroup(int leaderFd, uint nOpen, uint iters, ref double scale, scope double[] values, sparkles.profiling.counters.perf_group.GroupTimeBase base = GroupTimeBase(0LU, 0LU)) @safeReads a PERF_FORMAT_GROUP group from leaderFd (nOpen counters opened,
values returned in fd order). On success fills values`[0 .. `nOpen`]` with the
per-iteration averages, multiplex-corrected by the *pass's* enabled/running
deltas against base (see `GroupTimeBase`), sets scale to
`round3(runningΔ/enabledΔ)` (`1` = no multiplexing), and returns `true`.
On a short/interrupted read returns `false` and leaves values/scale
untouched (the caller fills `nan`); on a pass the PMU never scheduled
(`groupNeverRan`) returns `false` with scale = 0 — the zero counts
are the kernel's <not counted> state, not measurements.
readScaledGroup((field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0], (field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen, (parameter) uint itersiters, (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.scalescale, (local variable) double[63] valuesvalues[], (local variable) const(sparkles.profiling.counters.perf_group.GroupTimeBase) basebase))
{
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.totaltotal = double.(constant) double double.nan = nannan;
return (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
}
(alias) object.size_t = ulongsize_t (local variable) ulong slotslot;
foreach ((parameter) ulong ii, (parameter) int fdfd; (field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds)
{
if ((local variable) int fdfd < 0)
continue;
const (local variable) const(double) perIterperIter = (local variable) double[63] valuesvalues[(local variable) ulong slotslot++];
if ((local variable) ulong ii == 0)
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.totaltotal = (local variable) const(double) perIterperIter;
else
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts[(local variable) ulong ii - 1] = (local variable) const(double) perIterperIter;
}
return (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
}
/// Enables/disables the group for window measurement — no `RESET`,
/// so edge snapshots stay cumulative (see `PerfGroup.enable`).
void void sparkles.profiling.counters.syscalls.SyscallGroup.enable() @safeEnables/disables the group for window measurement — no RESET,
so edge snapshots stay cumulative (see PerfGroup.enable``).
enable() @safe
{
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (alias) groupIoctl = void sparkles.profiling.counters.perf_group.groupIoctl(int leaderFd, uint request) @safeSends a group-wide perf_event ioctl to the group leader leaderFd.
groupIoctl;
if ((field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened)
void sparkles.profiling.counters.perf_group.groupIoctl(int leaderFd, uint request) @safeSends a group-wide perf_event ioctl to the group leader leaderFd.
groupIoctl((field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0], (constant) int core.sys.linux.perf_event.PERF_EVENT_IOC_ENABLE = 9216Ioctls that can be done on a perf event fd:
PERF_EVENT_IOC_ENABLE);
}
/// ditto
void void sparkles.profiling.counters.syscalls.SyscallGroup.disable() @safeEnables/disables the group for window measurement — no RESET,
so edge snapshots stay cumulative (see PerfGroup.enable).
disable() @safe
{
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (alias) groupIoctl = void sparkles.profiling.counters.perf_group.groupIoctl(int leaderFd, uint request) @safeSends a group-wide perf_event ioctl to the group leader leaderFd.
groupIoctl;
if ((field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened)
void sparkles.profiling.counters.perf_group.groupIoctl(int leaderFd, uint request) @safeSends a group-wide perf_event ioctl to the group leader leaderFd.
groupIoctl((field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0], (constant) int core.sys.linux.perf_event.PERF_EVENT_IOC_DISABLE = 9217PERF_EVENT_IOC_DISABLE);
}
/// Captures one window-edge reading.
(struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot sparkles.profiling.counters.syscalls.SyscallSnapshot sparkles.profiling.counters.syscalls.SyscallGroup.snapshot() const @safeCaptures one window-edge reading.
snapshot() const @safe
{
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (alias) snapshotGroup = sparkles.profiling.counters.perf_group.GroupSnapshot sparkles.profiling.counters.perf_group.snapshotGroup(int leaderFd, uint nOpen) @safeCaptures a window-edge snapshot of the group led by leaderFd.
snapshotGroup;
return (field) bool sparkles.profiling.counters.syscalls.SyscallGroup.openedopened
? (struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot(sparkles.profiling.counters.perf_group.GroupSnapshot sparkles.profiling.counters.perf_group.snapshotGroup(int leaderFd, uint nOpen) @safeCaptures a window-edge snapshot of the group led by leaderFd.
snapshotGroup((field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds[0], (field) int sparkles.profiling.counters.syscalls.SyscallGroup.nOpennOpen)) : (struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot();
}
/// The syscall-count deltas across one window, as window $(B totals)
/// (`iters = 1`).
(struct) sparkles.profiling.counters.syscalls.SyscallStatsPer-iteration syscall counts of one counting pass. total is every syscall
(raw_syscalls:sys_enter); counts[i] is the per-iteration count of the
tracepoint named named[i] (nan if that tracepoint could not be opened).
SyscallStats sparkles.profiling.counters.syscalls.SyscallStats sparkles.profiling.counters.syscalls.SyscallGroup.windowStats(in sparkles.profiling.counters.syscalls.SyscallSnapshot a, in sparkles.profiling.counters.syscalls.SyscallSnapshot b) const pure nothrow @safeThe syscall-count deltas across one window, as window totals
(iters = 1).
windowStats(in (struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot (parameter) const(sparkles.profiling.counters.syscalls.SyscallSnapshot) aa, in (struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot (parameter) const(sparkles.profiling.counters.syscalls.SyscallSnapshot) bb)
const @safe pure nothrow
{
import (package) sparklessparkles.(package) sparkles.profilingprofiling.(package) sparkles.profiling.counterscounters.(module) sparkles.profiling.counters.perf_groupShared perf_event counter-group mechanics: the ENABLE/DISABLE counting
bracket and the PERF_FORMAT_GROUP scaled read. Both the hardware-counter
group (perf.d) and the syscall-tracepoint group (syscalls.d) open a
perf_event group led by an fd, bracket a benchmark's timed body with the
same ioctls, and read the group with the same layout (nr, time_enabled,
time_running, then one value per opened counter). This module holds that
common core so a change to the scaling/rounding is made once, not twice.
perf_group : (alias) windowDeltas = bool sparkles.profiling.counters.perf_group.windowDeltas(in sparkles.profiling.counters.perf_group.GroupSnapshot a, in sparkles.profiling.counters.perf_group.GroupSnapshot b, ref double scale, scope double[] values) pure nothrow @nogc @safeWindow deltas between two edge snapshots of one group: fills
values[0 .. a.n] with the window's multiplex-corrected $(B totals)
(iters = 1), sets scale, and returns true — same gate vocabulary
as readScaledGroup, plus one gate the pass path cannot hit: a window
across which the group's enabled time never advanced (the group was
never enabled) yields false with values/scale untouched — zero
deltas there would be fabricated counts, not measurements.
windowDeltas;
(struct) sparkles.profiling.counters.syscalls.SyscallStatsPer-iteration syscall counts of one counting pass. total is every syscall
(raw_syscalls:sys_enter); counts[i] is the per-iteration count of the
tracepoint named named[i] (nan if that tracepoint could not be opened).
SyscallStats (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) ulong sparkles.profiling.counters.syscalls.SyscallStats.itersiters = 1;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) const(string)[] sparkles.profiling.counters.syscalls.SyscallStats.namednamed = (field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_;
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts = new double[]((field) const(string)[] sparkles.profiling.counters.syscalls.SyscallGroup.names_names_.(field) ulong const(string[]).lengthlength);
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts[] = double.(constant) double double.nan = nannan;
double[1 + maxNamed] (local variable) double[63] valuesvalues;
if (!bool sparkles.profiling.counters.perf_group.windowDeltas(in sparkles.profiling.counters.perf_group.GroupSnapshot a, in sparkles.profiling.counters.perf_group.GroupSnapshot b, ref double scale, scope double[] values) pure nothrow @nogc @safeWindow deltas between two edge snapshots of one group: fills
values`[0 .. `a`.n]` with the window's multiplex-corrected **totals**
(`iters = 1`), sets scale, and returns `true` — same gate vocabulary
as `readScaledGroup`, plus one gate the pass path cannot hit: `a` window
across which the group's `enabled` time never advanced (the group was
never enabled) yields `false` with values/scale`` untouched — zero
deltas there would be fabricated counts, not measurements.
windowDeltas((parameter) const(sparkles.profiling.counters.syscalls.SyscallSnapshot) aa.(field) sparkles.profiling.counters.perf_group.GroupSnapshot sparkles.profiling.counters.syscalls.SyscallSnapshot.gg, (parameter) const(sparkles.profiling.counters.syscalls.SyscallSnapshot) bb.(field) sparkles.profiling.counters.perf_group.GroupSnapshot sparkles.profiling.counters.syscalls.SyscallSnapshot.gg, (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.scalescale, (local variable) double[63] valuesvalues[]))
{
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.totaltotal = double.(constant) double double.nan = nannan;
return (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
}
(alias) object.size_t = ulongsize_t (local variable) ulong slotslot;
foreach ((parameter) ulong ii, (parameter) const(int) fdfd; (field) int[] sparkles.profiling.counters.syscalls.SyscallGroup.fds[leader(total), named...]; -1 = unavailable
fds)
{
if ((local variable) const(int) fdfd < 0)
continue;
const (local variable) const(double) totaltotal = (local variable) double[63] valuesvalues[(local variable) ulong slotslot++];
if ((local variable) ulong ii == 0)
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double sparkles.profiling.counters.syscalls.SyscallStats.totaltotal = (local variable) const(double) totaltotal;
else
(local variable) sparkles.profiling.counters.syscalls.SyscallStats ss.(field) double[] sparkles.profiling.counters.syscalls.SyscallStats.countscounts[(local variable) ulong ii - 1] = (local variable) const(double) totaltotal;
}
return (local variable) sparkles.profiling.counters.syscalls.SyscallStats ss;
}
}
/// One cumulative window-edge reading of the syscall group.
struct (struct) sparkles.profiling.counters.syscalls.SyscallSnapshotOne cumulative window-edge reading of the syscall group.
SyscallSnapshot
{
package (struct) sparkles.profiling.counters.perf_group.GroupSnapshotOne cumulative PERF_FORMAT_GROUP reading at a window edge — a pure
read(2), no ioctl, no RESET — so an outer window candidate and
inner in-body windows can overlap freely: each computes its own deltas
between its own two edges.
GroupSnapshot (field) sparkles.profiling.counters.perf_group.GroupSnapshot sparkles.profiling.counters.syscalls.SyscallSnapshot.gg;
}
}
else
{
/// Non-Linux stub: syscall counters are permanently unavailable.
struct SyscallGroup
{
private static immutable CapabilityAbsence[1] stubAbsence = [
CapabilityAbsence(Capability.eventTracing, "not Linux"),
];
bool available() const @safe pure nothrow @nogc => false;
const(string)[] names() const @safe pure nothrow @nogc => null;
string status() const @safe pure nothrow => "unavailable (not Linux)";
CapabilityReport capabilities() const @safe pure nothrow @nogc
=> CapabilityReport(Capability.none, stubAbsence[]);
static SyscallGroup tryOpen(bool, const(string)[]) @safe pure nothrow @nogc
=> SyscallGroup();
void close() @safe pure nothrow @nogc {}
void enable() @safe pure nothrow @nogc {}
void disable() @safe pure nothrow @nogc {}
SyscallSnapshot snapshot() const @safe pure nothrow @nogc
=> SyscallSnapshot();
SyscallStats count(Timed, Between)(scope Timed, scope Between, uint, uint = 1)
{
assert(false, "syscall counters are Linux-only");
}
SyscallStats windowStats(in SyscallSnapshot, in SyscallSnapshot)
const @safe pure nothrow @nogc
=> assert(false, "syscall counters are Linux-only");
}
/// Off Linux: an empty window-edge marker with the same name.
struct SyscallSnapshot
{
}
}
// Whichever body the platform built (real or stub) satisfies the backend
// contract, including the optional named-columns primitive.
static assert((template instance) sparkles.profiling.counters.capability.isCounterBackend!(sparkles.profiling.counters.syscalls.SyscallGroup)isCounterBackend!(struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup);
static assert((template instance) sparkles.profiling.counters.capability.hasNamedColumns!(sparkles.profiling.counters.syscalls.SyscallGroup)hasNamedColumns!(struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup);
static assert((template instance) sparkles.profiling.counters.capability.hasSnapshot!(sparkles.profiling.counters.syscalls.SyscallGroup)hasSnapshot!(struct) sparkles.profiling.counters.syscalls.SyscallGroupThe syscall tracepoint counter group (Linux). tryOpen once; count
brackets one benchmark's timed body per iteration.
SyscallGroup);