0

I am coding a script that outputs information about the system used. I would like to add a function that prints out how much memory the system uses, but so far I have found functions like the one below, that prints only the app memory usage and the total memory.

Do you know by chance if there is a method in Swift, maybe contained directly in the Foundation framework, that allows to check the whole system memory usage?

func getMemoryUsedAndDeviceTotalInMegabytes() -> (Float, Float) {
    
    var used_megabytes: Float = 0
    let total_bytes = Float(ProcessInfo.processInfo.physicalMemory)
    let total_megabytes = total_bytes / 1024.0 / 1024.0
    var info = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
    let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
        $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
            task_info(
                mach_task_self_,
                task_flavor_t(MACH_TASK_BASIC_INFO),
                $0,
                &count
            )
        }
    }
    if kerr == KERN_SUCCESS {
        let used_bytes: Float = Float(info.resident_size)
        used_megabytes = used_bytes / 1024.0 / 1024.0
    }
    return (used_megabytes, total_megabytes)
}
  • [This](https://stackoverflow.com/questions/33855998/how-to-get-hardware-details-in-swift) may help you. – Ptit Xav Feb 21 '22 at 19:08
  • `host_statistics()` and `host_statistics64()` are in the `System` framework. You'll also need `host_page_size()`. You can also call `sysctl()` with "hw.memsize". – Daniel Widdis Feb 25 '22 at 14:44

0 Answers0