Vorssaint-utils System Monitor APIs for CPU, GPU, and Memory Statistics

The Vorssaint-utils system monitor reads hardware statistics using native macOS kernel interfaces—Mach host_statistics for CPU metrics, IOKit service matching for GPU utilization, and Mach VM statistics combined with sysctlbyname for memory data.

Vorssaint-utils is a macOS utility library that provides real-time hardware monitoring capabilities through its SystemMonitor component. The implementation avoids third-party dependencies by calling directly into macOS kernel frameworks, delivering accurate CPU, GPU, and memory statistics for menu-bar widgets and system panels.

CPU Monitoring via Mach host_statistics

The CPU monitoring implementation in Sources/Vorssaint/Services/SystemMonitor/SystemMonitor.swift utilizes the Mach kernel's host_statistics function to retrieve raw tick counters. The readCPUUsage() method (lines 85-100) queries the HOST_CPU_LOAD_INFO flavor to obtain user, system, idle, and nice tick counts from host_cpu_load_info.

The function computes utilization by comparing busy ticks (user + system + nice) against total ticks since the previous sample, yielding a normalized Double between 0 and 1.

private func readCPUUsage() -> Double? {
    var info = host_cpu_load_info()
    var count = mach_msg_type_number_t(
        MemoryLayout<host_cpu_load_info>.stride / MemoryLayout<integer_t>.stride
    )
    let host = mach_host_self()
    defer { mach_port_deallocate(mach_task_self_, host) }

    let kr = withUnsafeMutablePointer(to: &info) {
        $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
            host_statistics(host, HOST_CPU_LOAD_INFO, $0, &count)
        }
    }
    guard kr == KERN_SUCCESS else { return nil }

    let user = UInt64(info.cpu_ticks.0)
    let system = UInt64(info.cpu_ticks.1)
    let idle = UInt64(info.cpu_ticks.2)
    let nice = UInt64(info.cpu_ticks.3)

    let busy = user + system + nice
    let total = busy + idle
    defer { previousCPUTicks = (busy, total) }

    guard let previous = previousCPUTicks, total > previous.total else { return nil }
    return Double(busy - previous.busy) / Double(total - previous.total)
}

This delta calculation ensures accurate utilization percentages across sampling intervals by tracking the previous tick counts in previousCPUTicks.

GPU Monitoring via IOKit PerformanceStatistics

For GPU metrics, the system monitor interfaces with IOKit to query graphics accelerator services. The readGPUUsage() method (lines 111-140) searches for services matching "IOAccelerator" using IOServiceGetMatchingServices, then extracts the "Device Utilization %" field from the PerformanceStatistics dictionary.

The implementation iterates through accelerator entries via IOIteratorNext, reading properties with IORegistryEntryCreateCFProperty and converting the integer percentage to a floating-point value between 0 and 1.

private static func readGPUUsage() -> Double? {
    var iterator = io_iterator_t()
    guard IOServiceGetMatchingServices(kIOMainPortDefault,
        IOServiceMatching("IOAccelerator"),
        &iterator) == kIOReturnSuccess else { return nil }
    defer { IOObjectRelease(iterator) }

    while case let entry = IOIteratorNext(iterator), entry != 0 {
        defer { IOObjectRelease(entry) }
        guard let ref = IORegistryEntryCreateCFProperty(entry,
                "PerformanceStatistics" as CFString,
                kCFAllocatorDefault, 0),
              let stats = ref.takeRetainedValue() as? [String: Any],
              let utilization = stats["Device Utilization %"] as? Int
        else { continue }
        return Double(utilization) / 100.0
    }
    return nil
}

As implemented in Vorssaint-utils, this approach provides hardware-level GPU utilization without requiring proprietary graphics SDKs or driver-specific implementations.

Memory Monitoring via Mach VM Statistics and sysctl

Memory statistics rely on two distinct kernel interfaces. The SystemInfo.memoryUsage() helper (defined in Sources/Vorssaint/Support/SystemInfo.swift) queries host_statistics64 with the HOST_VM_INFO64 flavor to retrieve VM statistics including active, inactive, wired, and compressed page counts. These raw page counts convert to byte values stored as UInt64 in the snapshot struct (lines 34-49).

Memory pressure detection uses the readMemoryPressure() method (lines 45-52), which calls sysctlbyname with the "kern.memorystatus_vm_pressure_level" parameter:

private static func readMemoryPressure() -> MemoryPressure {
    var level: Int32 = 0
    var size = MemoryLayout<Int32>.size
    guard sysctlbyname("kern.memorystatus_vm_pressure_level",
                       &level, &size, nil, 0) == 0
    else { return .unknown }
    return MemoryPressure(kernelLevel: level)
}

The snapshot struct caches these values alongside CPU and GPU data, enabling efficient UI updates without redundant kernel calls during each refresh cycle.

Implementation Architecture and Feature Flags

The monitoring capabilities are gated by feature flags defined in Sources/Vorssaint/Core/FeatureCatalog.swift. The monitorCPU, monitorGPU, and monitorMemory boolean flags control whether the respective kernel APIs initialize during SystemMonitor startup, allowing conditional compilation of hardware monitoring features.

Key files in the Vorssaint-utils monitoring subsystem:

These low-level macOS APIs provide Vorssaint-utils with zero-dependency hardware monitoring suitable for menu-bar applications requiring minimal resource overhead.

Summary

  • CPU metrics: host_statistics with HOST_CPU_LOAD_INFO flavor reads Mach tick counters; utilization calculated from user, system, nice, and idle ticks in readCPUUsage()
  • GPU metrics: IOKit IOServiceGetMatchingServices locates "IOAccelerator" services; PerformanceStatistics dictionary provides "Device Utilization %" parsed by readGPUUsage()
  • Memory metrics: host_statistics64 with HOST_VM_INFO64 captures VM page statistics via SystemInfo.memoryUsage(); sysctlbyname retrieves pressure levels in readMemoryPressure()
  • Architecture: Feature flags in FeatureCatalog.swift control initialization; SystemMonitor.swift orchestrates sampling and snapshot generation for UI consumption

Frequently Asked Questions

Do these Vorssaint-utils system monitor APIs work on Apple Silicon Macs?

Yes. The Mach kernel APIs (host_statistics, host_statistics64) and IOKit interfaces are architecture-agnostic and function identically on both Intel and Apple Silicon (M1/M2/M3) Macs. The "IOAccelerator" service matching correctly identifies the integrated GPU on Apple Silicon as well as discrete GPUs on Intel models, making the Vorssaint-utils system monitor APIs portable across all modern macOS hardware.

What is the performance overhead of calling these kernel APIs?

The overhead is negligible for menu-bar applications. Each API call completes in microseconds: host_statistics retrieves pre-accumulated kernel counters, IOKit property reads access cached registry entries, and sysctlbyname queries static kernel variables. The Vorssaint-utils implementation caches results between UI updates to prevent redundant system calls during high-frequency refreshes.

Why does Vorssaint-utils use Mach APIs instead of higher-level Foundation frameworks?

Mach kernel interfaces provide the lowest latency and most accurate hardware metrics available on macOS. Higher-level frameworks like ProcessInfo lack GPU utilization data and provide only coarse memory statistics. Direct kernel access ensures Vorssaint-utils displays real-time CPU, GPU, and memory pressure data without polling delays or abstraction overhead introduced by intermediate layers.

Can these APIs be used in sandboxed Mac App Store applications?

No. The host_statistics Mach API and IOKit registry access require entitlements such as com.apple.security.temporary-exception.mach-lookup.host-special-port or specific IOKit client permissions, which Apple does not grant to App Store applications. Vorssaint-utils targets distributed (non-App Store) macOS apps where these entitlements are permissible through standard code signing outside the App Store sandbox.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →