6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-11-20

#ソースと使用例

ソース
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使用率とメモリ使用量を取得する

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?