Skip to content

Commit

Permalink
fix memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
noppefoxwolf committed Jul 20, 2021
1 parent 57227ea commit ad83457
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
2 changes: 1 addition & 1 deletion Sources/DebugMenu/Entity/Device.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public class Device {
String(format: "%.1f%%", cpuUsage() * 100.0)
}

public func cpuUsage() -> Float {
public func cpuUsage() -> Double {
CPU.usage()
}

Expand Down
22 changes: 9 additions & 13 deletions Sources/DebugMenu/Entity/Device/CPU.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,29 @@
import Foundation

class CPU {
static func usage() -> Float {
static func usage() -> Double {
let ids = threadIDs()
var totalUsage: Float = 0
var totalUsage: Double = 0
for id in ids {
let usage = threadUsage(id: id)
totalUsage += usage
}
return totalUsage
}

static func threadIDs() -> [UInt32] {
var threadList = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
static func threadIDs() -> [thread_inspect_t] {
var threadList: thread_act_array_t?
var threadCount = UInt32(MemoryLayout<mach_task_basic_info_data_t>.size / MemoryLayout<natural_t>.size)
let result = withUnsafeMutablePointer(to: &threadList) {
$0.withMemoryRebound(to: thread_act_array_t?.self, capacity: 1) {
task_threads(mach_task_self_, $0, &threadCount)
}
}
let result = task_threads(mach_task_self_, &threadList, &threadCount)
if result != KERN_SUCCESS { return [] }
var ids: [UInt32] = []
var ids: [thread_inspect_t] = []
for index in (0..<Int(threadCount)) {
ids.append(threadList[index])
ids.append(threadList![index])
}
return ids
}

static func threadUsage(id: UInt32) -> Float {
static func threadUsage(id: thread_inspect_t) -> Double {
var threadInfo = thread_basic_info()
var threadInfoCount = UInt32(THREAD_INFO_MAX)
let result = withUnsafeMutablePointer(to: &threadInfo) {
Expand All @@ -46,6 +42,6 @@ class CPU {
if result != KERN_SUCCESS { return 0 }
let isIdle = threadInfo.flags == TH_FLAGS_IDLE
// CPU使用率がスケール調整済みのため`TH_USAGE_SCALE`で除算し戻す
return !isIdle ? Float(threadInfo.cpu_usage) / Float(TH_USAGE_SCALE) : 0
return !isIdle ? Double(threadInfo.cpu_usage) / Double(TH_USAGE_SCALE) : 0
}
}

0 comments on commit ad83457

Please sign in to comment.