Skip to content
systemcoding.dev
Systems Programming

Check Resource Usage with getrusage

Read CPU time, peak memory, page faults and context switches for your own process with getrusage on Linux with glibc 2.40, and know which fields are filled.

7 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the C, Arm and Apple logos.

A process that "feels slow" has usually spent its time in one of four places: running your code, running kernel code on your behalf, waiting for the disk, or waiting for the scheduler. The getrusage system call splits those apart for you without a profiler, a tracer or a single extra dependency. This post shows the smallest complete program that reads your own process's usage, explains every field that matters on Linux, and points out the two places where the numbers surprise people. If you are new to how a process is laid out in the first place, a guide to processes on Linux is the right background, but nothing here depends on it.

The code targets Linux 6.12 and glibc 2.40, compiled with GCC 14 as C17. getrusage is specified by POSIX.1-2024 in <sys/resource.h>, and the Linux man page getrusage(2) documents which fields the kernel actually maintains.

What getrusage returns

The call has the signature int getrusage(int who, struct rusage *usage). The who argument chooses the scope:

whoMeaning
RUSAGE_SELFAll threads of the calling process, added together
RUSAGE_CHILDRENEvery child that has terminated and been waited for, plus their waited-for descendants
RUSAGE_THREADOnly the calling thread. Linux specific, needs _GNU_SOURCE, added in Linux 2.6.26

The result is a struct rusage. POSIX only requires the first two members, ru_utime and ru_stime. Linux fills these and several more:

FieldWhat it counts on Linux
ru_utimeCPU time spent in user mode, as a struct timeval
ru_stimeCPU time spent in kernel mode on behalf of the process
ru_maxrssPeak resident set size, in kilobytes
ru_minfltPage faults served without disk I/O
ru_majfltPage faults that needed disk I/O
ru_inblockFilesystem block reads
ru_oublockFilesystem block writes
ru_nvcswVoluntary context switches, such as blocking on I/O
ru_nivcswInvoluntary context switches, such as losing the CPU at the end of a time slice

The remaining members (ru_ixrss, ru_idrss, ru_isrss, ru_nswap, ru_msgsnd, ru_msgrcv, ru_nsignals) are present in the struct but are not maintained by Linux, so they read as zero. Treat them as padding.

The smallest complete program

The program below burns some CPU, touches some memory, and prints what the kernel recorded. It is deliberately a single file with no helper library.

usage.cc
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/time.h>

static void burn_cpu(void)
{
    volatile unsigned long sum = 0;
    for (unsigned long i = 0; i < 200000000UL; i++)
        sum += i;
}

static void touch_memory(size_t bytes)
{
    char *p = malloc(bytes);
    if (p == NULL) {
        perror("malloc");
        exit(1);
    }
    memset(p, 0xAB, bytes);
    free(p);
}

int main(void)
{
    burn_cpu();
    touch_memory(64UL * 1024 * 1024);

    struct rusage ru;
    if (getrusage(RUSAGE_SELF, &ru) != 0) {
        perror("getrusage");
        return 1;
    }

    printf("user   %ld.%06ld s\n", (long)ru.ru_utime.tv_sec, (long)ru.ru_utime.tv_usec);
    printf("system %ld.%06ld s\n", (long)ru.ru_stime.tv_sec, (long)ru.ru_stime.tv_usec);
    printf("maxrss %ld KiB\n", ru.ru_maxrss);
    printf("minflt %ld\n", ru.ru_minflt);
    printf("majflt %ld\n", ru.ru_majflt);
    printf("nvcsw  %ld\n", ru.ru_nvcsw);
    printf("nivcsw %ld\n", ru.ru_nivcsw);
    return 0;
}

Build it with gcc -std=c17 -O1 -o usage usage.c. The volatile on sum stops the compiler from deleting the loop, which at higher optimization levels it would do because the result is never used. The 64 MiB memset matters too: malloc of that size is served by mmap, and the kernel does not give the process real pages until they are written. Without the memset, ru_maxrss would barely move.

A run on a quiet machine prints something like this. The exact numbers differ on every run and every machine, so read the shape, not the digits:

Text
user   0.214519 s
system 0.031204 s
maxrss 67584 KiB
minflt 16543
majflt 0
nvcsw  0
nivcsw 3

Reading the output

user is the loop. system is mostly the kernel zeroing and mapping those 64 MiB, which is why it is non-zero even though the program never calls anything that looks like a system call in the loop. The minflt figure of roughly 16,000 follows from the arithmetic: 64 MiB divided by a 4 KiB page is 16,384 pages, and each first touch of a fresh anonymous page raises one minor fault. On a system with 16 KiB pages (some arm64 kernels) the count would be four times smaller, which is a useful reminder that fault counts are not portable between page sizes.

majflt is zero because nothing was read from disk. A major fault means the kernel had to go to storage to satisfy the access, for example when a memory-mapped file is touched for the first time and is not in the page cache. A rising majflt is the clearest sign that a process is waiting on I/O rather than computing.

nvcsw counts times the process gave up the CPU on its own, usually by blocking. nivcsw counts times the scheduler took the CPU away. A CPU-bound loop shows many involuntary switches and few voluntary ones; a network server idling on epoll_wait shows the reverse. The ratio tells you which kind of process you have before you open a profiler.

Measuring a child instead of yourself

Often the thing you want to measure is another program. RUSAGE_CHILDREN reports on children you have already waited for, so the pattern is fork, exec, wait, then read:

childusage.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        execlp("sort", "sort", "/usr/share/dict/words", "-o", "/dev/null", (char *)NULL);
        perror("execlp");
        _exit(127);
    }

    int wstatus;
    if (waitpid(pid, &wstatus, 0) < 0) {
        perror("waitpid");
        return 1;
    }

    struct rusage ru;
    getrusage(RUSAGE_CHILDREN, &ru);
    printf("child user   %ld.%06ld s\n", (long)ru.ru_utime.tv_sec, (long)ru.ru_utime.tv_usec);
    printf("child system %ld.%06ld s\n", (long)ru.ru_stime.tv_sec, (long)ru.ru_stime.tv_usec);
    printf("child maxrss %ld KiB\n", ru.ru_maxrss);
    return 0;
}
Text
child user   0.186403 s
child system 0.012871 s
child maxrss 23812 KiB

Two details here are easy to miss. First, the child's usage is added to the parent's RUSAGE_CHILDREN counters only when the parent reaps it with wait, waitpid or wait4. If you call getrusage before waiting, you read zeros. Second, for RUSAGE_CHILDREN the ru_maxrss field is the largest maxrss among all waited-for children, not the sum, so it answers "how big did the biggest child get", which is rarely what people expect. The shell's time builtin is built on exactly this idea, and wait4(2) hands you a struct rusage for one specific child if you need it per child.

Where the numbers mislead

ru_maxrss is in kilobytes on Linux but in bytes on macOS and some other systems. Code that prints it directly is correct on one and off by a factor of 1024 on the other, so divide by 1024 only under a platform check.

CPU times have limited resolution. Older kernels charged time in whole scheduler ticks; modern kernels with CONFIG_VIRT_CPU_ACCOUNTING_GEN or the default tick-based accounting still split user and system time by sampling, so a very short run can show a surprising split. For a stable number, measure something that runs for at least a few tenths of a second, as the loop above does.

RUSAGE_SELF is a snapshot of totals from process start. To measure one phase, call getrusage before and after and subtract. Subtracting the timeval fields needs a borrow when the microsecond difference goes negative, which is the usual off-by-one-second bug.

delta.cc
#include <sys/resource.h>
#include <sys/time.h>

static double tv_seconds(struct timeval tv)
{
    return (double)tv.tv_sec + (double)tv.tv_usec / 1e6;
}

double cpu_seconds_between(const struct rusage *a, const struct rusage *b)
{
    double user = tv_seconds(b->ru_utime) - tv_seconds(a->ru_utime);
    double sys = tv_seconds(b->ru_stime) - tv_seconds(a->ru_stime);
    return user + sys;
}

Converting to a double first avoids the borrow logic entirely. At these magnitudes a double holds microseconds exactly, so nothing is lost.

When getrusage is the wrong tool

getrusage reports totals, not where they came from. It cannot tell you which function burned the CPU, so once it points at user time, move to a sampling profiler. It also says nothing about other processes, so for system-wide contention use the pressure stall interface. And for limits rather than measurement, the sibling call is setrlimit, which caps the same resources getrusage reports.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.