Skip to content

Commit

Permalink
On Linux, try to use /proc/loadavg to get instaneous load (#2218)
Browse files Browse the repository at this point in the history
The /proc/loadavg file includes the traditional 1-, 5- and 15-minute
loads plus an instantaneous count of processes that are ready to run.
This lets us respond faster to new processes being launched by other
processes.
  • Loading branch information
entrope committed Mar 30, 2023
1 parent 2d9083b commit 367fbf8
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,36 @@ double GetLoadAverage() {
}
#else
double GetLoadAverage() {
# if defined(__linux__)
// Only try to open the file once.
static int fd = -1;
if (fd == -1) {
fd = open("/proc/loadavg", O_RDONLY);
if (fd < 0) {
fd = -2;
}
}

if (fd >= 0) {
char buf[65], *p;
ssize_t nbr = pread(fd, buf, sizeof(buf) - 1, 0);
// Load average should be at least "1 5 9 n/", where we want the "n".
if (nbr > 7) {
buf[nbr] = '\0';
p = strchr(buf, ' ');
if (p) {
p = strchr(p + 1, ' ');
}
if (p) {
p = strchr(p + 1, ' ');
}
if (p && (unsigned(p[1]) - '0' <= 9)) {
return atoi(p + 1);
}
}
}
# endif

double loadavg[3] = { 0.0f, 0.0f, 0.0f };
if (getloadavg(loadavg, 3) < 0) {
// Maybe we should return an error here or the availability of
Expand Down

0 comments on commit 367fbf8

Please sign in to comment.