Printing the Uptime and Idle Time of processor (Linux)
/proc/uptime file contains only two values in seconds, one is the Uptime of the processor (the time upto which the processor was on) and another is the idle time of all the processors (cores).
So idle is always higher than the uptime in case of multicore processors.
The following C program shows the uptime and idle time in terms of days hours and minutes. This is a very simple program just tells you how to convert a given time in days, hours, minutes and seconds.
using C FILE concept, the /proc/uptime file is been read using the “r” mode and values are fetched and then converted into days, hours and seconds.
1: // printing the uptime and idle time
2: #include <stdio.h>
3: /* Summarize a duration of time to standard output. TIME is the
4: amount of time, in seconds, and LABEL is a short descriptive label. */
5: void print_time (char* label, long time)
7: /* Conversion constants. */
8: const long minute = 60;
9: const long hour = minute * 60;
10: const long day = hour * 24;
11: /* Produce output. */
12: printf (“%s: %ld days, %ld:%02ld:%02ld\n”, label, time / day,
13: (time % day) / hour, (time % hour) / minute, time % minute);
15: int main ()
17: FILE* fp;
18: double uptime, idle_time;
19: /* Read the system uptime and accumulated idle time from /proc/uptime. */
20: fp = fopen (“/proc/uptime”, “r”);
21: fscanf (fp, “%lf %lf\n”, &uptime, &idle_time);
22: fclose (fp);
23: /* Summarize it. */
24: print_time (“uptime “, (long) uptime);
25: print_time (“idle time”, (long) idle_time);
26: return 0;