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:
-
System calls and APIs:
- On Linux/Unix systems, data can be read from
/procfiles (e.g.,/proc/loadavgfor 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.
- On Linux/Unix systems, data can be read from
-
Using monitoring libraries and tools:
- Libraries that wrap system calls, such as
libprocps. - Calling external utilities via
popen(), such astop,vmstat,uptime, and parsing their output.
- Libraries that wrap system calls, such as
-
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;
}