burkey.co /docs/libflint/macos
index macos
~/docs/libflint/macos.md
libflint

Macos

libflint·Platform

Process CPU and memory sampling on macOS. The declarations in lfmacos.h are available only on Apple platforms, and CMake builds the implementation only there.

Usage#

Create a sample with new_ProcessData(), then call update_process() at intervals. The first successful update establishes a baseline and reports zero CPU usage.

ProcessData *pd = new_ProcessData();
if (pd != NULL) {
    for (int i = 0; i < 10; i++) {
        if (update_process(getpid(), pd) != 0) {
            break;
        }
        printf("CPU: %.2f\n", pd->percent_cpu);
        sleep(1);
    }
    destroy_ProcessData(pd);
}

Call destroy_ProcessData() when finished to free the sample.

Structs#

ProcessData#

CPU and memory measurements for a process. Use the same process ID for successive updates of a sample.

typedef struct {
    double total_user_time;
    double total_kernel_time;
    double last_total_consumed;
    double percent_cpu;

    uint64_t virtual_memory;
    uint64_t resident_memory;

    time_t timestamp;
    time_t last_timestamp;
} ProcessData;

total_user_time and total_kernel_time are cumulative CPU time in seconds. virtual_memory and resident_memory are sizes in bytes. percent_cpu is 100 times the CPU time used since the previous sample, divided by elapsed wall-clock seconds. It is 0 when this is the first successful update or the wall clock did not advance a full second, and it can exceed 100 when the process uses more than one core. After a successful update, last_total_consumed equals total_user_time + total_kernel_time; before the first update it is -1.0. timestamp and last_timestamp are time_t seconds. During the update the interval is the new time() value minus the previous last_timestamp. After success both timestamps hold that new sample time.

Functions#

new_ProcessData#

Allocates a sample with last_total_consumed set to -1.0 and all other fields zero. Returns NULL on allocation failure.

ProcessData *new_ProcessData(void);

destroy_ProcessData#

Frees the sample. Safe to call with NULL.

void destroy_ProcessData(ProcessData *pd);

update_process#

Updates CPU and memory measurements for pid. Returns 0 on success or -1 if proc is NULL or the system queries fail.

CPU usage is measured over whole wall-clock seconds. The first update, or an update with no positive elapsed interval, reports zero CPU usage. Space updates at least one second apart to obtain a useful interval.

int update_process(pid_t pid, ProcessData *proc);