Problem
The cpuUsage() function in SentrySystemWrapper calculates total CPU usage by summing threadInfo.cpu_usage for each thread. However, it omits a necessary division by TH_USAGE_SCALE (1000), which is the scale factor for thread_basic_info.cpu_usage per Apple's Mach API.
This causes the reported CPU usage to be 1000× larger than the actual value. For example, a true usage of 0.1% would be reported as 100%.
Evidence
- Apple docs:
cpu_usage is a scaled value; divide by TH_USAGE_SCALE (1000) to get percentage
- SentryThreadHandle.cpp (line 175): correctly uses
static_cast<float>(data.cpu_usage) / TH_USAGE_SCALE
- Current code:
usage += Float(threadInfo.cpu_usage) / processorCount — missing the scale division
Proposed fix
usage += Float(threadInfo.cpu_usage) / Float(TH_USAGE_SCALE) / processorCount
TH_USAGE_SCALE is defined in <mach/thread_info.h> (1000) and is available when importing Darwin.
Location
Sources/Swift/Helper/SentrySystemWrapper.swift — cpuUsage() method
Note
The existing unit test testCPUUsageReportsData only asserts (0.0...100.0).contains(cpuUsage.doubleValue). It can pass by chance when the process is nearly idle and the raw unscaled value stays under 100. Consider adding a test that verifies reasonable percentage values under load.
Problem
The
cpuUsage()function inSentrySystemWrappercalculates total CPU usage by summingthreadInfo.cpu_usagefor each thread. However, it omits a necessary division byTH_USAGE_SCALE(1000), which is the scale factor forthread_basic_info.cpu_usageper Apple's Mach API.This causes the reported CPU usage to be 1000× larger than the actual value. For example, a true usage of 0.1% would be reported as 100%.
Evidence
cpu_usageis a scaled value; divide byTH_USAGE_SCALE(1000) to get percentagestatic_cast<float>(data.cpu_usage) / TH_USAGE_SCALEusage += Float(threadInfo.cpu_usage) / processorCount— missing the scale divisionProposed fix
TH_USAGE_SCALEis defined in<mach/thread_info.h>(1000) and is available when importing Darwin.Location
Sources/Swift/Helper/SentrySystemWrapper.swift—cpuUsage()methodNote
The existing unit test
testCPUUsageReportsDataonly asserts(0.0...100.0).contains(cpuUsage.doubleValue). It can pass by chance when the process is nearly idle and the raw unscaled value stays under 100. Consider adding a test that verifies reasonable percentage values under load.