Sorry to hijack, but we’re facing a similar issue. We use task_for_pid
to profile memory consumption during the automated testing of our iOS application. Specifically, we need to programmatically gather memory usage metrics—current, peak, and final—during UI tests to analyze and optimize resource-heavy screens. Tracking these memory metrics is critical to preventing and resolving memory-related crashes.
Here’s what we’re doing:
- Extracting the application’s PID: We retrieve the PID of the app under test from
XCUIApplication.debugDescription
. - Profiling memory consumption: We use
task_for_pid
in combination with task_info and the TASK_VM_INFO
flavor to collect memory data like the physical footprint and peak memory usage. Here’s a simplified example of our implementation:
private func getMemoryUsage(for pid: pid_t) -> (current: Double, peak: Double)? {
var task: mach_port_t = 0
let kern = task_for_pid(mach_task_self_, pid, &task)
guard kern == KERN_SUCCESS else {
return nil
}
return getMemoryUsage(for: task)
}
private func getMemoryUsage(for task: mach_port_t) -> (current: Double, peak: Double)? {
var vmInfo = task_vm_info_data_t()
var vmCount = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size) / 4
let kern: kern_return_t = withUnsafeMutablePointer(to: &vmInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
task_info(task, task_flavor_t(TASK_VM_INFO), $0, &vmCount)
}
}
guard kern == KERN_SUCCESS else {
return nil
}
let currentMemoryUsage = vmInfo.phys_footprint
let peakMemoryUsage = UInt64(bitPattern: vmInfo.ledger_phys_footprint_peak)
return (current: currentMemoryUsage, peak: peakMemoryUsage)
}
We understand that task_for_pid
is a powerful API that Apple has restricted to specific use cases, primarily for developer tools. However, we currently lack any alternative APIs to programmatically collect memory metrics during testing.
Are there any supported or recommended APIs we can use to achieve this functionality?