Sobes.tech
Junior — Middle

What methods can be used to obtain information about current system loads?

sobes.tech AI

Answer from AI

To obtain information about current system loads in C/C++, several approaches can be used:

  1. System calls and APIs:

    • On Linux/Unix systems, data can be read from /proc files (e.g., /proc/loadavg for the average CPU load).
    • Use functions like getloadavg() to get the average load.
    • Calls to sysconf() can be used to get information about the number of processors.
  2. Using monitoring libraries and tools:

    • Libraries that wrap system calls, such as libprocps.
    • Calling external utilities via popen(), such as top, vmstat, uptime, and parsing their output.
  3. Manual metric collection:

    • Using functions to measure execution time, memory usage, and CPU usage within the program.

Example of reading the average load using getloadavg():

#include <stdio.h>
#include <stdlib.h>

int main() {
    double loadavg[3];
    if (getloadavg(loadavg, 3) != -1) {
        printf("Load averages: 1 min: %.2f, 5 min: %.2f, 15 min: %.2f\n", loadavg[0], loadavg[1], loadavg[2]);
    } else {
        printf("Failed to get load averages\n");
    }
    return 0;
}