pub struct Sampler { /* private fields */ }Expand description
Session-scoped handle for hardware performance counters.
When you create a Sampler, it loads Apple’s private kperf.framework and
kperfdata.framework, detects which CPU you’re running on, opens the
corresponding PMC event database, and force-acquires all hardware counters.
“Force-acquiring” means taking control of the counters that macOS normally
reserves for the OS Power Manager. Without this step, you can only access
a subset of the available counters. The previous force-all state is saved
at construction and restored when the Sampler is dropped, so other tools
that rely on those counters (like powermetrics) are only affected while
the Sampler is alive.
You should typically create one Sampler per process. Creating multiple
Samplers is safe but will interfere with the save/restore of the
force-all-counters state, since each one independently saves and restores
the sysctl value on drop.
A Sampler is Send + Sync because all of its operations are
stateless sysctl calls. Use thread to create per-thread
ThreadSamplers that read the actual counter values.
Implementations§
Source§impl Sampler
impl Sampler
Sourcepub fn new() -> Result<Self, SamplerError>
pub fn new() -> Result<Self, SamplerError>
Creates a new sampler for the current CPU.
§Errors
Returns SamplerError if a framework fails to load, the CPU is
unrecognized, or counter acquisition fails (typically due to missing
root privileges).
Sourcepub unsafe fn release(&self) -> Result<(), SamplerError>
pub unsafe fn release(&self) -> Result<(), SamplerError>
Releases force-acquired counters back to the OS Power Manager.
Restores the force_all_ctrs state saved at construction. This performs
the same teardown step as Drop, but without freeing the database.
Intended for static samplers that outlive the measurement phase (e.g.
a Criterion harness) and need to relinquish counters before process
exit.
§Safety
The caller must ensure no ThreadSampler created from this Sampler
is currently running. Releasing counters while a ThreadSampler is
actively counting produces undefined hardware counter behavior.
§Errors
Returns SamplerError::FailedToForceAllCounters if the kernel
rejects the sysctl write.
Sourcepub const fn database(&self) -> Database<'_>
pub const fn database(&self) -> Database<'_>
A safe view of the PMC event database for the detected CPU.
Sourcepub fn thread<const N: usize>(
&self,
events: [Event; N],
) -> Result<ThreadSampler<'_, N>, SamplerError>
pub fn thread<const N: usize>( &self, events: [Event; N], ) -> Result<ThreadSampler<'_, N>, SamplerError>
Creates a ThreadSampler configured for the given events.
The returned ThreadSampler is !Send + !Sync and must be used on
the thread that created it.
§Errors
Returns SamplerError if any event is unavailable on the current CPU
or if counter programming fails.