Created
June 22, 2018 02:10
-
-
Save masaya-takagi/e72580660bb73803030afbb06dc73cff to your computer and use it in GitHub Desktop.
Swift で CPU の使用率を表示する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/xcrun swift | |
import Cocoa | |
let host_port = mach_host_self() | |
var prev_cpu_load = host_cpu_load_info_data_t() | |
var cpu_load = host_cpu_load_info_data_t() | |
var count = mach_msg_type_number_t(MemoryLayout<host_cpu_load_info_data_t>.size / MemoryLayout<integer_t>.size) | |
var user : natural_t | |
var system : natural_t | |
var idle : natural_t | |
let cpu_usage = {(cpu_load_info : host_cpu_load_info_data_t) -> host_cpu_load_info_data_t in | |
var load_info = cpu_load_info | |
return withUnsafePointer(to: &load_info) { (pointer : UnsafePointer<host_cpu_load_info_data_t>) -> host_cpu_load_info_data_t in | |
let raw = OpaquePointer(pointer) | |
let host_info = host_info_t(raw) | |
host_statistics(host_port, HOST_CPU_LOAD_INFO, host_info, &count); | |
return pointer.pointee | |
} | |
} | |
prev_cpu_load = cpu_usage(prev_cpu_load) | |
while true { | |
sleep(1) | |
cpu_load = cpu_usage(cpu_load) | |
user = cpu_load.cpu_ticks.0 - prev_cpu_load.cpu_ticks.0; | |
system = cpu_load.cpu_ticks.1 - prev_cpu_load.cpu_ticks.1; | |
idle = cpu_load.cpu_ticks.2 - prev_cpu_load.cpu_ticks.2; | |
print((Double)(user + system) / (Double)(system + user + idle) * 100.0) | |
prev_cpu_load = cpu_load; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment