How to Get CPU Usage in C – Simple Step‑by‑Step Guide
In this article
Yes, you can get CPU usage in C by reading system‑specific interfaces such as /proc/stat on Linux or the GetSystemTimes API on Windows and then calculating the percentage yourself.
What You'll Need
- A C compiler (gcc, clang, MSVC, etc.)
- Basic development environment (terminal or IDE)
- Access to platform headers:
unistd.handstdio.hfor Linux,windows.hfor Windows - If you prefer the PDH library on Windows, link against
Pdh.lib
Step‑By‑Step
- Decide which operating system you are targeting. The method differs dramatically between Unix‑like systems and Windows. The code examples below are split into two sections; pick the one that matches your build target.
-
Linux: Read the raw CPU counters from
/proc/stat.Open the file, read the first line that starts with
cpu, and split the fields. The fields represent time spent in user, nice, system, idle, iowait, irq, softirq, steal, guest, and guest_nice – all measured in "jiffies" (ticks of the kernel timer).#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { unsigned long long user, nice, system, idle, iowait, irq, softirq, steal; } CpuStat; int read_cpu_stat(CpuStat *s) { FILE *fp = fopen("/proc/stat", "r"); if (!fp) return -1; char line[256]; if (!fgets(line, sizeof(line), fp)) { fclose(fp); return -1; } fclose(fp); // Example line: "cpu 4705 150 2332 136789 123 0 45 0 0 0" sscanf(line, "cpu %llu %llu %llu %llu %llu %llu %llu %llu", &s->user, &s->nice, &s->system, &s->idle, &s->iowait, &s->irq, &s->softirq, &s->steal); return 0; }This function fills a
CpuStatstructure with the current counters. -
Linux: Compute the usage over a time interval.
CPU usage is not a single instant value; you need two snapshots separated by a short delay (e.g., 100 ms). Subtract the earlier values from the later ones, sum all fields to get the total delta, and then calculate the non‑idle portion.
#include <unistd.h> // for usleep float cpu_usage_percent() { CpuStat prev, cur; if (read_cpu_stat(&prev) != 0) return -1.0f; usleep(100000); // 100 ms if (read_cpu_stat(&cur) != 0) return -1.0f; unsigned long long prev_idle = prev.idle + prev.iowait; unsigned long long cur_idle = cur.idle + cur.iowait; unsigned long long prev_total = prev.user + prev.nice + prev.system + prev.idle + prev.iowait + prev.irq + prev.softirq + prev.steal; unsigned long long cur_total = cur.user + cur.nice + cur.system + cur.idle + cur.iowait + cur.irq + cur.softirq + cur.steal; unsigned long long total_delta = cur_total - prev_total; unsigned long long idle_delta = cur_idle - prev_idle; if (total_delta == 0) return 0.0f; return (float)(total_delta - idle_delta) * 100.0f / (float)total_delta; }Call
cpu_usage_percent()whenever you need an up‑to‑date reading. -
Windows: Use
GetSystemTimesto obtain idle, kernel, and user times.This API is available from Windows XP onward and does not require extra libraries.
#include <windows.h> #include <stdio.h> typedef struct { FILETIME idle; FILETIME kernel; FILETIME user; } CpuTimes; int get_cpu_times(CpuTimes *t) { return GetSystemTimes(&t->idle, &t->kernel, &t->user); }The
FILETIMEvalues are 64‑bit counts of 100‑nanosecond intervals since system start. -
Windows: Calculate usage between two snapshots.
#include <stdint.h> static ULONGLONG ft_to_ull(const FILETIME *ft) { return ((ULONGLONG)ft->dwHighDateTime << 32) | ft->dwLowDateTime; } float windows_cpu_usage() { CpuTimes prev, cur; if (!get_cpu_times(&prev)) return -1.0f; Sleep(100); // 100 ms if (!get_cpu_times(&cur)) return -1.0f; ULONGLONG prev_idle = ft_to_ull(&prev.idle); ULONGLONG prev_kernel = ft_to_ull(&prev.kernel); ULONGLONG prev_user = ft_to_ull(&prev.user); ULONGLONG cur_idle = ft_to_ull(&cur.idle); ULONGLONG cur_kernel = ft_to_ull(&cur.kernel); ULONGLONG cur_user = ft_to_ull(&cur.user); ULONGLONG prev_total = (prev_kernel + prev_user); ULONGLONG cur_total = (cur_kernel + cur_user); ULONGLONG total_delta = cur_total - prev_total; ULONGLONG idle_delta = cur_idle - prev_idle; if (total_delta == 0) return 0.0f; return (float)(total_delta - idle_delta) * 100.0f / (float)total_delta; }This function returns a floating‑point percentage similar to the Linux version.
-
Optional Windows alternative: PDH (Performance Data Helper).
If you need a more flexible solution that can query multiple counters, initialise a PDH query with
PdhAddCounterfor the "\Processor(_Total)\% Processor Time" counter, collect data withPdhCollectQueryData, and read the formatted value withPdhGetFormattedCounterValue. The PDH route requires linking againstPdh.liband handling COM‑style error codes. -
Compile and run.
On Linux, compile with
gcc -O2 -o cpu_usage cpu_usage.c. On Windows, use the Visual Studio command prompt:cl /O2 cpu_usage.c. Run the resulting executable; it will print a line such as "CPU Usage: 12.3%".
Common Mistakes
- Reading
/proc/statonly once and treating the raw idle value as the usage. The file reports cumulative counters; you must compare two snapshots. - Dividing by the wrong total. The total must include all fields (user, system, idle, etc.) – omitting
iowaitorstealskews the result. - Using
Sleep(0)or a delay that is too short on Windows. The scheduler may not give the process enough time to observe a change, resulting in a zero delta. - Neglecting to cast the 64‑bit
FILETIMEvalues correctly, which can cause overflow on 32‑bit builds. - Linking against the wrong library on Windows (e.g., forgetting
Pdh.libwhen using PDH).
Tips
- Cache the previous snapshot in static variables if you need to query frequently; this avoids the extra
usleep/Sleepcall when you already have a recent reading. - For multi‑core systems, the
cpuline in/proc/statalready aggregates all cores. If you need per‑core data, read the linescpu0,cpu1, etc., and apply the same calculation per line. - When using PDH, enable a 1‑second sample interval to reduce overhead. The PDH API also provides a callback mechanism if you want asynchronous updates.
- Remember that the numbers are percentages of a single logical processor. On a machine with 8 logical CPUs, a total usage of 400 % means all cores are fully busy.
- Use
sysconf(_SC_CLK_TCK)on Linux if you need to convert jiffies to seconds for reporting or logging.
Troubleshooting
- File not found or permission denied when opening
/proc/stat. This file is world‑readable on standard Linux installations. If you see an error, you are likely running inside a restricted container or chroot that does not expose/proc. Ensure the container is started with the--procflag or mountprocmanually. - Zero or negative percentages. Verify that the time interval between snapshots is non‑zero. Increase the
usleep/Sleepdelay to at least 50 ms and re‑test. - Compilation errors about undefined symbols on Windows. Make sure you include
Windows.hbefore any other Windows‑specific headers and link againstKernel32.lib(default) forGetSystemTimes. For PDH, addPdh.libto the linker input. - Unexpected high values (e.g., >100 %). This usually means you added the idle time twice – on Windows the
kerneltime already includes idle, so the correct total iskernel + userwithout adding idle separately. - Program crashes on 32‑bit builds. The conversion from
FILETIMEtoULONGLONGmust use a 64‑bit type; on 32‑bit compilers you may need to enable/W4warnings and cast carefully.
Frequently Asked Questions
Can I get CPU usage without a delay?
Not reliably. The counters are cumulative; a single snapshot tells you how much time has been spent since boot, not the current load. A short interval (50‑200 ms) gives a practical approximation.
Is there a single cross‑platform library?
Libraries such as libstatgrab or Boost.Process provide abstractions, but they add external dependencies. The native approaches shown above work everywhere without extra packages.
How do I monitor CPU usage in a separate thread?
Create a thread that sleeps for the chosen interval, reads the counters, computes the delta, and stores the result in a thread‑safe variable (e.g., std::atomic or a mutex‑protected float).
What about measuring usage of a specific process?
Process‑specific usage requires reading /proc/[pid]/stat on Linux or using the GetProcessTimes API on Windows, then applying the same delta calculation. The principles are identical, only the source of the counters changes.
Do hyper‑threaded cores affect the percentage?
Hyper‑threading makes the OS report logical CPUs. The aggregated cpu line still represents the sum of all logical threads, so the percentage can reach 200 % on a dual‑core hyper‑threaded system, 400 % on a quad‑core with HT, etc.
Can I log CPU usage to a file?
Yes. Open a file with fopen("cpu.log", "a") and write the timestamp plus the percentage each time you call the measurement function. Remember to flush or close the file periodically to avoid data loss.