Edited at

Swift:macのCPU使用率を取得する


ソースと使用例


ソース

import Darwin

public class CPU {

private let loadInfoCount: mach_msg_type_number_t!
private let machHost = mach_host_self()
private var loadPrevious = host_cpu_load_info()

init() {
loadInfoCount = UInt32(MemoryLayout<host_cpu_load_info_data_t>.size / MemoryLayout<integer_t>.size)
}

private func hostCPULoadInfo() -> host_cpu_load_info {
var size: mach_msg_type_number_t = loadInfoCount
let hostInfo = host_cpu_load_info_t.allocate(capacity: 1)

let _ = hostInfo.withMemoryRebound(to: integer_t.self, capacity: Int(size)) { (pointer) -> kern_return_t in
return host_statistics(machHost, HOST_CPU_LOAD_INFO, pointer, &size)
}
let data = hostInfo.move()
hostInfo.deallocate()

return data
}

public func usageCPU() -> (system: Double, user: Double, idle: Double) {
let load = hostCPULoadInfo()
let userDiff = Double(load.cpu_ticks.0 - loadPrevious.cpu_ticks.0)
let sysDiff = Double(load.cpu_ticks.1 - loadPrevious.cpu_ticks.1)
let idleDiff = Double(load.cpu_ticks.2 - loadPrevious.cpu_ticks.2)
let niceDiff = Double(load.cpu_ticks.3 - loadPrevious.cpu_ticks.3)
loadPrevious = load
let totalTicks = sysDiff + userDiff + idleDiff + niceDiff
let sys = 100.0 * sysDiff / totalTicks
let user = 100.0 * userDiff / totalTicks
let idle = 100.0 * idleDiff / totalTicks
return (sys, user, idle)
}

}



使用例

let cpu = CPU()

var timer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { (t) in
let res = cpu.usageCPU()
Swift.print("システム: \(res.system)")
Swift.print("ユーザ: \(res.user)")
Swift.print("アイドル: \(res.idle)")
Swift.print("CPU使用率: \(round(10.0 * (res.system + res.user)) / 10.0)\n")
}


参考

beltex/SystemKit

SwiftでアプリのCPU使用率とメモリ使用量を取得する