thermal

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: 11 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 thermal reports macOS thermal state, AC/battery power source, and optional SoC power readings for benchmark qualification and energy-per-token governing.

Thermal state is read from Foundation's NSProcessInfo.thermalState, power source information is read from IOKit's IOPowerSources API, and optional SoC energy/wattage readings come from github.com/tmc/apple/x/powersample. All calls use purego bindings with zero cgo.

Basic usage:

snap := thermal.TakeSnapshot()
fmt.Printf("state=%s power=%s\n", snap.State, snap.PowerSource)

gov := thermal.NewGovernor(thermal.DefaultGate())
rep, err := gov.Measure(ctx, func(ctx context.Context) error {
	return runBenchmark(ctx)
})
if err != nil {
	log.Fatal(err)
}
if rep.GateErr != nil {
	log.Printf("benchmark disqualified: %v", rep.GateErr)
}
if jpt, ok := rep.JoulesPerToken(tokens); ok {
	fmt.Printf("efficiency=%.4f J/tok\n", jpt)
}
Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/thermal"
)

func main() {
	before := thermal.Snapshot{
		State:       thermal.Nominal,
		PowerSource: thermal.PowerSource{Kind: thermal.AC, BatteryPercent: -1},
	}
	after := before
	if err := thermal.CheckBenchmarkGate(before, after); err != nil {
		fmt.Println("disqualified:", err)
		return
	}
	fmt.Printf("qualified: %.3f J/tok\n", thermal.JoulesPerToken(4.5, 150))
}
Output:
qualified: 0.030 J/tok

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrThermalThrottled indicates the thermal state exceeded the gate's maximum.
	ErrThermalThrottled = errors.New("thermal: state exceeds benchmark gate")
	// ErrThermalRise indicates the thermal state rose during the benchmark window.
	ErrThermalRise = errors.New("thermal: state increased during benchmark")
	// ErrNotOnAC indicates the host was not on AC power when AC was required.
	ErrNotOnAC = errors.New("thermal: host is not on AC power")
)

Functions

func CheckBenchmarkGate

func CheckBenchmarkGate(before, after Snapshot) error

CheckBenchmarkGate evaluates before and after snapshots against DefaultGate.

func JoulesPerToken

func JoulesPerToken(energyJ float64, tokens int) float64

JoulesPerToken computes energy efficiency in joules per token. It returns 0 if tokens <= 0 or energyJ < 0.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/thermal"
)

func main() {
	fmt.Printf("%.4f J/tok\n", thermal.JoulesPerToken(12.5, 500))
}
Output:
0.0250 J/tok

func Watch

func Watch(ctx context.Context, interval time.Duration, fn func(Snapshot)) error

Watch calls fn with a fresh Snapshot immediately and then on every interval until ctx is canceled, returning ctx.Err(). If interval <= 0, it defaults to 250ms.

Types

type Gate

type Gate struct {
	// MaxState is the highest thermal state permitted before and after a run.
	MaxState State
	// RequireAC rejects runs where either the before or after snapshot is not on AC power.
	RequireAC bool
	// AllowStateIncrease permits after.State > before.State as long as both
	// remain at or below MaxState.
	AllowStateIncrease bool
}

Gate defines thermal and power qualification criteria for benchmarks. The zero value requires Nominal thermal state, disallows thermal rise, and does not require AC power. Use DefaultGate for standard benchmark qualification.

func DefaultGate

func DefaultGate() Gate

DefaultGate returns the default benchmark qualification gate: Nominal thermal state throughout the run and AC power required.

func (Gate) Check

func (g Gate) Check(before, after Snapshot) error

Check verifies that before and after snapshots satisfy the gate.

type Governor

type Governor struct {
	Gate           Gate
	SampleInterval time.Duration
}

Governor wraps a Gate and powersample interval to qualify and meter workloads.

func NewGovernor

func NewGovernor(gate Gate) *Governor

NewGovernor returns a Governor configured with gate and a 250ms power sample interval.

func (*Governor) CheckBenchmarkGate

func (g *Governor) CheckBenchmarkGate(before, after Snapshot) error

CheckBenchmarkGate evaluates before and after snapshots against the governor's Gate.

func (*Governor) Measure

func (g *Governor) Measure(ctx context.Context, work func(context.Context) error) (RunReport, error)

Measure runs work while capturing before/after snapshots and optional powersample measurements, then evaluates the governor's Gate. If powersample cannot start or stop, Measure degrades gracefully by recording the error in RunReport.After.PowerErr rather than failing the run.

func (*Governor) Watch

func (g *Governor) Watch(ctx context.Context, fn func(Snapshot)) error

Watch polls thermal and power state using g.SampleInterval until ctx is canceled.

type PowerSource

type PowerSource struct {
	Kind           PowerSourceKind
	BatteryPercent int // 0..100, or -1 if no battery is present
	Charging       bool
}

PowerSource describes the host's active power source and battery state. When no battery is present (for example on a desktop Mac), BatteryPercent is -1.

func CurrentPowerSource

func CurrentPowerSource() PowerSource

CurrentPowerSource queries IOKit's IOPowerSources API for the active power source and internal battery status.

func (PowerSource) String

func (p PowerSource) String() string

String formats the power source for human-readable output.

type PowerSourceKind

type PowerSourceKind int

PowerSourceKind identifies the host's active power source.

const (
	Unknown PowerSourceKind = iota
	AC
	Battery
	UPS
)

func (PowerSourceKind) String

func (k PowerSourceKind) String() string

String returns a lowercase name for the power source kind.

type RunReport

type RunReport struct {
	Before   Snapshot
	After    Snapshot
	Duration time.Duration
	GateErr  error
}

RunReport summarizes a governed workload execution.

func (RunReport) JoulesPerToken

func (r RunReport) JoulesPerToken(tokens int) (float64, bool)

JoulesPerToken computes joules per token from the run's combined SoC energy. It returns (0, false) if power measurements were unavailable or tokens <= 0.

type Snapshot

type Snapshot struct {
	Time        time.Time
	State       State
	PowerSource PowerSource
	// Power holds the SoC power/energy report when power sampling was
	// requested and succeeded. It is nil otherwise.
	Power *powersample.Report
	// PowerErr holds the error when power sampling was attempted and failed
	// (for example when IOReport and powermetrics privileges are unavailable).
	PowerErr error
}

Snapshot records a point-in-time observation of thermal state, power source, and optional SoC power/energy measurements.

func SampleSnapshot

func SampleSnapshot(ctx context.Context, window time.Duration) Snapshot

SampleSnapshot captures a Snapshot and attempts to measure SoC power over window using x/powersample. If window <= 0, it defaults to 250ms. If power sampling is unavailable, SampleSnapshot does not fail: it leaves Power nil and records the reason in PowerErr.

func TakeSnapshot

func TakeSnapshot() Snapshot

TakeSnapshot captures the current timestamp, thermal state, and power source without starting a power meter.

type State

type State int

State represents the macOS system thermal state reported by NSProcessInfo.

const (
	// Nominal indicates the thermal state is within normal limits.
	Nominal State = State(foundation.NSProcessInfoThermalStateNominal)
	// Fair indicates the thermal state is slightly elevated.
	Fair State = State(foundation.NSProcessInfoThermalStateFair)
	// Serious indicates the thermal state is high.
	Serious State = State(foundation.NSProcessInfoThermalStateSerious)
	// Critical indicates the thermal state is significantly impacting performance.
	Critical State = State(foundation.NSProcessInfoThermalStateCritical)
)

func CurrentState

func CurrentState() State

CurrentState returns the current system thermal state from NSProcessInfo.

func (State) String

func (s State) String() string

String returns a lowercase name for the thermal state.

Jump to

Keyboard shortcuts

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