timestral-coreai / swift /Sources /TimestralKit /SystemMemory.swift
jbilcke's picture
Publish Timestral CoreAI models, native Swift SDK and validated Python runtime
506f40d verified
Raw History Blame Contribute Delete
1.21 kB
import Darwin
import Foundation
public enum SystemMemory {
/// macOS free + inactive pages, matching the conservative available-memory
/// measure used for the original guarded conversion. Compressed pages are
/// not counted as immediately available.
public static func availableBytes() -> UInt64 {
var pages = vm_statistics64_data_t()
var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)
let result = withUnsafeMutablePointer(to: &pages) { pointer in
pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count)
}
}
guard result == KERN_SUCCESS else { return 0 }
return (UInt64(pages.free_count) + UInt64(pages.inactive_count)) * UInt64(getpagesize())
}
public static func residentBytes(processID: Int32) -> UInt64 {
var info = proc_taskinfo()
let expected = Int32(MemoryLayout<proc_taskinfo>.size)
let read = proc_pidinfo(processID, PROC_PIDTASKINFO, 0, &info, expected)
return read == expected ? info.pti_resident_size : 0
}
}