go-linux

Performance counters and sampling

Import github.com/alexfalkowski/go-linux/v2/perf to measure a bounded worker or CPU interval with Linux performance events. Open a counter or a fixed group, enable it around the work, then disable it and read a typed snapshot. The caller owns the resource and closes it after the final read.

runtime.LockOSThread()
defer runtime.UnlockOSThread()

flags := perf.ExcludeKernel | perf.ExcludeHypervisor
clock := perf.Config{Event: perf.Software(perf.TaskClock), Flags: flags}
faults := perf.Config{Event: perf.Software(perf.PageFaults), Flags: flags}
group, err := perf.OpenGroup(perf.CurrentThread(), clock, faults)
if err != nil {
    return err
}
defer group.Close()

if err := group.Enable(); err != nil {
    return err
}
runWorkerBatch()
if err := group.Disable(); err != nil {
    return err
}
reading, err := group.Read()
if err != nil {
    return err
}
fmt.Println(reading.Counts[0].Value, reading.Counts[1].Value)

The executable example measures the first write to a fresh page. perf.Open measures one event with the same control sequence. The first count includes time the thread spends in system calls. Linux’s TaskClock and CPUClock count time in both user and kernel mode even with ExcludeKernel set. Domain filtering depends on the event.

Target the workload

perf.CurrentThread() measures the OS thread that opens the event. Lock the Go goroutine to that thread through the measurement. perf.Thread(tid) identifies one numeric Linux thread in the caller’s PID namespace. Coordinate the target’s lifetime to avoid reuse of its TID. Using a process ID measures the thread-group leader. Use target.OnCPU(cpu) to count that thread only when it runs on the selected CPU, or perf.CPU(cpu) to measure across all threads on a CPU.

Set perf.Inherit for a task event to include new descendant tasks. For a group, use the flag on every event and let the target start descendants only after group creation. An inherited group with different membership can cause Read to return ECHILD.

Interpret a snapshot

Read returns raw counts with event IDs, cumulative enabled time, and cumulative running time. The times are unsigned nanoseconds. A group’s counts appear in the order supplied to OpenGroup, including the leader at index 0, and share the leader’s timing fields. ID and IDs query Linux’s event IDs independently of reading a snapshot. Counts remain unscaled. An event can spend less time running than enabled when it shares PMU resources. A zero running time precludes a multiplexing estimate.

Enable resumes counting. Disable retains values and timings. Reset clears the kernel’s current counts and preserves both timings. Linux can retain counts already accumulated from exited inherited tasks. For a new independent interval, use a fresh counter or take deltas between snapshots. Group operations control all members through the leader. Use Pinned or Exclusive on the leader or a standalone counter. A pinned event in a scheduling error state can report io.EOF on read. A group opens as one owned resource. Failure closes any events already created. Methods serialize access with Close. Callers coordinate the full measurement sequence.

Sample a worker

Use OpenSampler to locate events in a worker or correlate them with another observation. It opens one disabled event with an owned forward ring. Select fields such as SampleTID | SampleTime and enable the event for the work interval. The executable sampling example records the first write to an anonymous page and reads one record with a deadline.

Period requests the number of event units per sample. Linux can throttle sampling, and some software events report every occurrence when the sample includes SamplePeriod. Select a period appropriate to the event and workload.

RingPages is a power of two up to perf.MaxRingPages. Zero selects eight data pages in addition to the kernel metadata page. Mapping is subject to the kernel’s perf lock budget and the process’s memory lock limit.

Read with ReadRecord and bound the wait with SetReadDeadline. Closing the sampler interrupts pending reads. Disabling or exiting the target can leave an empty ring without an end-of-stream signal. Drain queued records after the work interval with TryReadRecord, which returns immediately and ignores the read deadline. Readers share one position. Each record and its slices remain valid after subsequent reads and close. If the first unmap fails, Close attempts to disable the event before closing its descriptor and reports any cleanup errors together. Retry Close to release the remaining mapping.

Inspect Record.Header.Type to choose the body. Sample fields include the instruction pointer, process/thread IDs, monotonic time, event ID, CPU, period, and a variable-length callchain with Linux’s context markers. Fields omitted from the configuration are zero. Sample and throttle times use the kernel’s CLOCK_MONOTONIC in nanoseconds without the caller’s time-namespace offset. Keep these values separate from wall time and Go’s I/O deadline clock.

When the ring fills, Linux discards incoming records and can report the loss in a later RecordLost after space becomes available. Losses at shutdown may never reach the reader. RecordLostSamples represents PMU-reported sample loss. Throttle and unthrottle records carry kernel IDs and timestamps. Unknown record types retain their header and opaque payload. A broken boundary or producer overrun returns an error at the current ring position. A complete record with a malformed body is consumed and returns a decode error.

DecodeRecord applies the same native-endian layout to one saved record. The caller supplies the original sample field selection and interprets timestamps in the producer’s clock domain. Its input supports the forward record format without sample_id_all trailers.

Kernel prerequisites and scope

A software event such as TaskClock is the portable starting point. Linux checks the target, measurement domains, perf_event_paranoid, capabilities, and syscall restrictions. Whole-CPU measurements have separate permissions. Direct syscall errors retain their Linux errno. When Go cannot register a sampler descriptor for polling, OpenSampler reports os.ErrNoDeadline. A hardware or raw event may fail on an absent PMU even when software counters work. Use Hardware for generic hardware events and Raw for a PMU-specific PERF_TYPE_RAW config word. Verify the raw encoding on the intended CPU. The perf security guide and perf_event_open manual describe Linux’s access checks and event types.

Sampling covers standalone forward rings with the fields described above. Sampling inheritance, grouped sampling, overwrite rings, and AUX hardware trace buffers require separate contracts. Cgroup-wide attachment, additional PMU config words, symbolization, and BPF program loading are outside the package scope. For live software checks, see perf verification.