@@ -276,10 +276,10 @@ public enum SystemMetrics {
276276 /// CPU usage is calculated as the number of CPU ticks used by this process between measurements.
277277 /// - Note: the first measurement will be calculated since the process' start time, since there's no
278278 /// previous measurement to take as reference.
279- private struct CPUUsageCalculator {
279+ internal struct CPUUsageCalculator {
280280 /// The number of ticks after system boot that the last CPU usage stat was taken.
281281 private var previousTicksSinceSystemBoot : Int = 0
282- /// The number of ticks the process actively used the CPU, as of the previous CPU usage measurement.
282+ /// The number of ticks the process actively used the CPU for , as of the previous CPU usage measurement.
283283 private var previousCPUTicks : Int = 0
284284
285285 mutating func getUsagePercentage( ticksSinceSystemBoot: Int , cpuTicks: Int ) -> Double {
@@ -288,6 +288,10 @@ public enum SystemMetrics {
288288 self . previousCPUTicks = cpuTicks
289289 }
290290 let ticksBetweenMeasurements = ticksSinceSystemBoot - self . previousTicksSinceSystemBoot
291+ guard ticksBetweenMeasurements > 0 else {
292+ return 0
293+ }
294+
291295 let cpuTicksBetweenMeasurements = cpuTicks - self . previousCPUTicks
292296 return Double ( cpuTicksBetweenMeasurements) * 100 / Double( ticksBetweenMeasurements)
293297 }
@@ -371,7 +375,8 @@ public enum SystemMetrics {
371375 var cpuUsage : Double = 0
372376 if cpuTicks > 0 {
373377 guard let uptimeString = uptimeFileContents. split ( separator: " " ) . first,
374- let uptimeSeconds = Float ( uptimeString)
378+ let uptimeSeconds = Float ( uptimeString) ,
379+ uptimeSeconds. isFinite
375380 else { return nil }
376381 let uptimeTicks = Int ( ceilf ( uptimeSeconds) ) * ticks
377382 cpuUsage = SystemMetrics . cpuUsageCalculator. getUsagePercentage ( ticksSinceSystemBoot: uptimeTicks, cpuTicks: cpuTicks)
0 commit comments