7.6 System Statistics

Two entries in /proc contain useful system statistics. The /proc/loadavg file contains information about the system load. The first three numbers represent the number of active tasks on the system—processes that are actually running—averaged over the last 1, 5, and 15 minutes. The next entry shows the instantaneous current number of runnable tasks—processes that are currently scheduled to run rather than being blocked in a system call—and the total number of processes on the system. The final entry is the process ID of the process that most recently ran.

The /proc/uptime file contains the length of time since the system was booted, as well as the amount of time since then that the system has been idle. Both are given as floating-point values, in seconds.

 
% cat /proc/uptime 
3248936.18 3072330.49 

The program in Listing 7.7 extracts the uptime and idle time from the system and displays them in friendly units.

Listing 7.7 (print-uptime.c) Print the System Uptime and Idle Time
#include <stdio.h> 
 
/* Summarize a duration of time to standard output. TIME is the 
   amount of time, in seconds, and LABEL is a short descriptive label.  */ 
 
void print_time (char* label, long time) 
{
  /* Conversion constants.  */ 
  const long minute = 60; 
  const long hour = minute * 60; 
  const long day = hour * 24; 
  /* Produce output.  */ 
  printf ("%s: %ld days, %ld:%02ld:%02ld\n", label, time / day, 
          (time % day) / hour, (time % hour) / minute, time % minute); 
} 
 
int main () 
{
  FILE* fp; 
  double uptime, idle_time; 
  /* Read the system uptime and accumulated idle time from /proc/uptime.  */ 
  fp = fopen ("/proc/uptime", "r"); 
  fscanf (fp, "%lf %lf\n", &uptime, &idle_time); 
  fclose (fp); 
  /* Summarize it.  */ 
  print_time ("uptime ", (long) uptime); 
  print_time ("idle time", (long) idle_time); 
  return 0; 
} 

The uptime command and the sysinfo system call (see Section 8.14, "sysinfo: Obtaining System Statistics") also can obtain the system's uptime. The uptime command also displays the load averages found in /proc/loadavg.