TechBuzzPro

How to Get CPU Usage in C – Simple Step‑by‑Step Guide

· 6 min read · Windows & PC

In this article
  1. What You'll Need
  2. Step‑By‑Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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.h and stdio.h for Linux, windows.h for Windows
  • If you prefer the PDH library on Windows, link against Pdh.lib

Step‑By‑Step

  1. 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.
  2. 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 CpuStat structure with the current counters.

  3. 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.

  4. Windows: Use GetSystemTimes to 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 FILETIME values are 64‑bit counts of 100‑nanosecond intervals since system start.

  5. 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.

  6. Optional Windows alternative: PDH (Performance Data Helper).

    If you need a more flexible solution that can query multiple counters, initialise a PDH query with PdhAddCounter for the "\Processor(_Total)\% Processor Time" counter, collect data with PdhCollectQueryData, and read the formatted value with PdhGetFormattedCounterValue. The PDH route requires linking against Pdh.lib and handling COM‑style error codes.

  7. 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/stat only 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 iowait or steal skews 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 FILETIME values correctly, which can cause overflow on 32‑bit builds.
  • Linking against the wrong library on Windows (e.g., forgetting Pdh.lib when using PDH).

Tips

  • Cache the previous snapshot in static variables if you need to query frequently; this avoids the extra usleep/Sleep call when you already have a recent reading.
  • For multi‑core systems, the cpu line in /proc/stat already aggregates all cores. If you need per‑core data, read the lines cpu0, 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 --proc flag or mount proc manually.
  • Zero or negative percentages. Verify that the time interval between snapshots is non‑zero. Increase the usleep/Sleep delay to at least 50 ms and re‑test.
  • Compilation errors about undefined symbols on Windows. Make sure you include Windows.h before any other Windows‑specific headers and link against Kernel32.lib (default) for GetSystemTimes. For PDH, add Pdh.lib to the linker input.
  • Unexpected high values (e.g., >100 %). This usually means you added the idle time twice – on Windows the kernel time already includes idle, so the correct total is kernel + user without adding idle separately.
  • Program crashes on 32‑bit builds. The conversion from FILETIME to ULONGLONG must use a 64‑bit type; on 32‑bit compilers you may need to enable /W4 warnings 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.