metalcounters

package
v0.6.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

Overview

Package metalcounters provides a zero-cgo wrapper around Metal GPU timestamp counter sampling for both Metal 3 (metal.MTLCounterSampleBuffer) and Metal 4 (metal.MTL4CounterHeap).

Use Probe to inspect timestamp counter availability on a metal.MTLDevice, NewSampler (or NewHeapSampler on Metal 4 devices) to allocate a sample buffer, and BeginCalibration to correlate GPU timestamps with CPU nanoseconds via metal.MTLDevice.SampleTimestampsGpuTimestamp:

dev := metal.MTLCreateSystemDefaultDevice()
s, err := metalcounters.NewSampler(dev, 64)
if err != nil {
	return err
}
defer s.Close()

cal := metalcounters.BeginCalibration(dev)
// Encode compute work with s.Sample(enc, i) or s.AttachComputePass(desc, 0, 1),
// commit, and wait until completed.
cal.Finish(dev)

nanos, err := s.ResolveNanos(cal)
if err != nil {
	return err
}
_ = nanos

The zero value of Sampler is not usable; construct one with NewSampler or NewHeapSampler and release the underlying Metal object with Sampler.Close.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/objectivec"
	"github.com/tmc/apple/x/metalcounters"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	s, err := metalcounters.NewSampler(dev, 4)
	if err != nil {
		panic(err)
	}
	defer s.Close()

	q := dev.NewCommandQueue()
	defer objectivec.ObjectFromID(q.GetID()).Release()

	cal := metalcounters.BeginCalibration(dev)
	cb := q.CommandBuffer()
	desc := metal.NewMTLComputePassDescriptor()
	defer desc.Release()
	if err := s.AttachComputePass(desc, 0, 1); err != nil {
		panic(err)
	}
	enc := cb.ComputeCommandEncoderWithDescriptor(desc)
	enc.EndEncoding()
	cb.Commit()
	cb.WaitUntilCompleted()
	cal.Finish(dev)

	nanos, err := s.ResolveRangeNanos(cal, 0, 2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("samples=%d valid=%v\n", len(nanos), nanos[1] >= nanos[0])
}
Output:
samples=2 valid=true

Index

Examples

Constants

View Source
const (
	// DontSample is the Metal sentinel (MTLCounterDontSample) telling a pass
	// attachment not to sample at that boundary.
	DontSample = ^uint(0)

	// ErrorTimestamp is the Metal sentinel (MTLCounterErrorValue) written into
	// a resolved timestamp slot when the GPU did not record a valid sample.
	ErrorTimestamp = ^uint64(0)
)

Variables

View Source
var (
	// ErrUnsupported is returned when the device or sampler backend does not
	// support the requested timestamp counter operation.
	ErrUnsupported = errors.New("metalcounters: timestamp counter sampling unsupported")

	// ErrClosed is returned when a method is called on a closed Sampler.
	ErrClosed = errors.New("metalcounters: sampler closed")

	// ErrInvalidCapacity is returned when NewSampler or NewHeapSampler is given
	// a non-positive capacity.
	ErrInvalidCapacity = errors.New("metalcounters: capacity must be positive")

	// ErrIndexOutOfRange is returned when a sample index or range exceeds the
	// sampler's capacity.
	ErrIndexOutOfRange = errors.New("metalcounters: sample index out of range")

	// ErrInvalidSample is returned by ResolveNanos / ResolveRangeNanos when a
	// resolved slot contains ErrorTimestamp.
	ErrInvalidSample = errors.New("metalcounters: unresolved or error timestamp sample")
)

Functions

This section is empty.

Types

type Backend

type Backend int

Backend identifies the underlying Metal counter storage backing a Sampler.

const (
	// BackendSampleBuffer uses a Metal 3 MTLCounterSampleBuffer.
	BackendSampleBuffer Backend = iota + 1

	// BackendCounterHeap uses a Metal 4 MTL4CounterHeap.
	BackendCounterHeap
)

func (Backend) String

func (b Backend) String() string

type Calibration

type Calibration struct {
	Start TimestampPair
	End   TimestampPair
}

Calibration maps raw GPU counter timestamps onto the CPU nanosecond clock domain using one or two correlated TimestampPair anchors.

For best accuracy across long GPU workloads, call BeginCalibration before committing GPU work and Calibration.Finish after the GPU work completes.

func BeginCalibration

func BeginCalibration(dev metal.MTLDevice) Calibration

BeginCalibration captures the opening (CPU, GPU) timestamp pair before GPU work. Pair it with Calibration.Finish after the command buffer finishes.

func Calibrate

func Calibrate(dev metal.MTLDevice) Calibration

Calibrate captures a two-point Calibration separated by a brief pause so the GPU-to-CPU clock ratio can be estimated even without bracketing a pass.

func (Calibration) Duration

func (c Calibration) Duration(startGPU, endGPU uint64) time.Duration

Duration converts a raw GPU timestamp interval [startGPU, endGPU] into a time.Duration. If endGPU < startGPU, it returns 0.

func (*Calibration) Finish

func (c *Calibration) Finish(dev metal.MTLDevice)

Finish captures the closing (CPU, GPU) timestamp pair after GPU work completes.

func (Calibration) Scale

func (c Calibration) Scale() float64

Scale returns the estimated CPU nanoseconds per GPU timestamp tick. When only a single anchor is present or the GPU delta is zero, it returns 1.0.

func (Calibration) ToNanos

func (c Calibration) ToNanos(gpuTimestamp uint64) uint64

ToNanos converts a raw GPU timestamp into the CPU nanosecond clock domain.

type Capabilities

type Capabilities struct {
	DeviceName string

	// CounterSets lists the names of all MTLCounterSet instances reported by the device.
	CounterSets []string

	// TimestampCounterSet reports whether the device exposes the common timestamp counter set.
	TimestampCounterSet bool

	// Sampling points supported by Metal 3 counter sample buffers.
	StageBoundary    bool
	DispatchBoundary bool
	BlitBoundary     bool
	DrawBoundary     bool

	// Metal3SampleBuffer reports whether allocating a shared MTLCounterSampleBuffer
	// for the timestamp counter set succeeds.
	Metal3SampleBuffer bool

	// Metal4CounterHeap reports whether the device supports Metal 4 and allocating
	// an MTL4CounterHeap of type MTL4CounterHeapTypeTimestamp succeeds.
	Metal4CounterHeap        bool
	Metal4TimestampEntrySize uint
	TimestampFrequency       uint64

	// Notes records non-fatal probe diagnostics returned by the driver.
	Notes []string
}

Capabilities reports the GPU timestamp counter features supported by a device.

func Probe

func Probe(dev metal.MTLDevice) Capabilities

Probe inspects dev for Metal 3 and Metal 4 timestamp counter support without panicking on nil devices or hosts without timestamp counters.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/x/metalcounters"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	caps := metalcounters.Probe(dev)
	fmt.Printf("ready=%v timestamp=%v\n", caps.Ready(), caps.TimestampCounterSet)
}
Output:
ready=true timestamp=true

func (Capabilities) Ready

func (c Capabilities) Ready() bool

Ready reports whether at least one GPU timestamp sampling backend is usable.

type Sampler

type Sampler struct {
	// contains filtered or unexported fields
}

Sampler manages a fixed-capacity Metal GPU timestamp buffer (either a Metal 3 metal.MTLCounterSampleBuffer or a Metal 4 metal.MTL4CounterHeap).

func NewHeapSampler

func NewHeapSampler(dev metal.MTLDevice, capacity int) (*Sampler, error)

NewHeapSampler allocates a Metal 4 metal.MTL4CounterHeap of type metal.MTL4CounterHeapTypeTimestamp with room for capacity samples.

It returns ErrUnsupported if dev is nil or does not support Metal 4 counter heaps.

func NewSampler

func NewSampler(dev metal.MTLDevice, capacity int) (*Sampler, error)

NewSampler allocates a Metal 3 shared metal.MTLCounterSampleBuffer for the device's timestamp counter set with room for capacity samples.

It returns ErrUnsupported if dev is nil or does not expose the timestamp counter set.

func (*Sampler) AttachComputePass

func (s *Sampler) AttachComputePass(desc metal.IMTLComputePassDescriptor, startIndex, endIndex int) error

AttachComputePass configures attachment 0 of desc to sample start and end timestamps into s. Pass a negative index for startIndex or endIndex to skip sampling that boundary (translated to DontSample).

func (*Sampler) AttachComputePassAt

func (s *Sampler) AttachComputePassAt(desc metal.IMTLComputePassDescriptor, attachmentIndex uint, startIndex, endIndex int) error

AttachComputePassAt configures the given attachment index of desc to sample start and end timestamps into s. Pass a negative index for startIndex or endIndex to skip sampling that boundary.

func (*Sampler) Backend

func (s *Sampler) Backend() Backend

Backend reports whether s is backed by Metal 3 MTLCounterSampleBuffer or Metal 4 MTL4CounterHeap.

func (*Sampler) Capacity

func (s *Sampler) Capacity() int

Capacity returns the number of timestamp slots in s.

func (*Sampler) Close

func (s *Sampler) Close() error

Close releases the underlying Metal counter buffer or heap. Close is idempotent.

func (*Sampler) CounterHeap

func (s *Sampler) CounterHeap() metal.MTL4CounterHeap

CounterHeap returns the underlying Metal 4 metal.MTL4CounterHeap, or nil if s is closed or backed by a Metal 3 sample buffer.

func (*Sampler) Invalidate

func (s *Sampler) Invalidate(start, count int) error

Invalidate invalidates entries [start, start+count) in a Metal 4 counter heap. The GPU must not be using the heap when this is called.

func (*Sampler) Resolve

func (s *Sampler) Resolve() ([]uint64, error)

Resolve resolves all capacity raw GPU timestamps from s on the CPU timeline. Callers must ensure GPU work writing into s has completed before calling Resolve.

func (*Sampler) ResolveNanos

func (s *Sampler) ResolveNanos(cal Calibration) ([]uint64, error)

ResolveNanos resolves all capacity timestamps and converts them to CPU-domain nanoseconds using cal. It returns ErrInvalidSample if any slot contains ErrorTimestamp.

func (*Sampler) ResolveRange

func (s *Sampler) ResolveRange(start, count int) ([]uint64, error)

ResolveRange resolves raw GPU timestamps for slots [start, start+count). Callers must ensure GPU work writing into s has completed first.

func (*Sampler) ResolveRangeNanos

func (s *Sampler) ResolveRangeNanos(cal Calibration, start, count int) ([]uint64, error)

ResolveRangeNanos resolves timestamps in [start, start+count) and converts them to CPU-domain nanoseconds using cal. It returns ErrInvalidSample if any slot in the range contains ErrorTimestamp.

func (*Sampler) Sample

func (s *Sampler) Sample(enc metal.MTLComputeCommandEncoder, index int) error

Sample encodes a GPU timestamp sample at index on enc with barrier=true. It requires a Metal 3 BackendSampleBuffer sampler.

func (*Sampler) SampleBlit

func (s *Sampler) SampleBlit(enc metal.MTLBlitCommandEncoder, index int, barrier bool) error

SampleBlit encodes a GPU timestamp sample at index on a blit command encoder.

func (*Sampler) SampleBuffer

func (s *Sampler) SampleBuffer() metal.MTLCounterSampleBuffer

SampleBuffer returns the underlying Metal 3 metal.MTLCounterSampleBuffer, or nil if s is closed or backed by a Metal 4 counter heap.

func (*Sampler) SampleWithBarrier

func (s *Sampler) SampleWithBarrier(enc metal.MTLComputeCommandEncoder, index int, barrier bool) error

SampleWithBarrier encodes a GPU timestamp sample at index on enc with the requested barrier flag. When barrier is false, the GPU may overlap adjacent dispatches across the sample point on concurrent encoders.

func (*Sampler) TimestampFrequency

func (s *Sampler) TimestampFrequency() uint64

TimestampFrequency returns the GPU timestamp tick frequency in Hz reported by metal.MTLDevice.QueryTimestampFrequency for Metal 4 counter heaps, or 0 for Metal 3 sample buffers (whose resolved timestamps are already in the SampleTimestamps GPU domain).

func (*Sampler) WriteCommandBufferTimestamp

func (s *Sampler) WriteCommandBufferTimestamp(cb metal.MTL4CommandBuffer, index int) error

WriteCommandBufferTimestamp encodes a Metal 4 GPU timestamp write directly on a metal.MTL4CommandBuffer at index. It requires a BackendCounterHeap sampler.

func (*Sampler) WriteTimestamp

func (s *Sampler) WriteTimestamp(enc metal.MTL4ComputeCommandEncoder, granularity metal.MTL4TimestampGranularity, index int) error

WriteTimestamp encodes a Metal 4 GPU timestamp write into s at index on enc. It requires a BackendCounterHeap sampler created with NewHeapSampler.

type TimestampPair

type TimestampPair struct {
	CPU uint64
	GPU uint64
}

TimestampPair holds a correlated CPU and GPU timestamp sampled simultaneously via metal.MTLDevice.SampleTimestampsGpuTimestamp.

func SampleTimestamps

func SampleTimestamps(dev metal.MTLDevice) TimestampPair

SampleTimestamps queries dev for a simultaneous (CPU, GPU) timestamp pair. It returns a zero TimestampPair if dev is nil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL