4

I need to find the system time since power is applied on a linux machine in my c code. Functions like 'time()' and gettimeofday() return the time since epoch and not since power on. How do I find the time or number of clock ticks since power on?

Thanks in advance!

user2437770
  • 81
  • 2
  • 2
  • 5
  • 2
    `uptime` gives it to you but I'm not sure if there's an API to access it or you'll have to call it as a command – Cfreak Jul 18 '13 at 15:48
  • 1
    possible duplicate of [What API do I call to get the system uptime?](http://stackoverflow.com/questions/1540627/what-api-do-i-call-to-get-the-system-uptime) – Cfreak Jul 18 '13 at 15:49

3 Answers3

8

This information is provided through the /proc filesystem API. Specifically, /proc/uptime. In C, just open it as a normal file and read one floating point number from it. It will be the amount of seconds since power on. If you read another FP value, it will be how many seconds the system has spent in total being idle. You're only interested in the first number though.

Example:

float uptime;
FILE* proc_uptime_file = fopen("/proc/uptime", "r");
fscanf(proc_uptime_file, "%f", &uptime);

This value is in seconds, floating point.

You can convert it back to clock ticks:

uptime * sysconfig(_SC_CLK_TCK);
Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
3

See: Wgat API do I call to get the System Time

Please see sysinfo() in

sys/sysinfo.h

struct sysinfo {
  long uptime;             /* Seconds since boot */
  unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
  unsigned long totalram;  /* Total usable main memory size */
  unsigned long freeram;   /* Available memory size */
  unsigned long sharedram; /* Amount of shared memory */
  unsigned long bufferram; /* Memory used by buffers */
  unsigned long totalswap; /* Total swap space size */
  unsigned long freeswap;  /* swap space still available */
  unsigned short procs;    /* Number of current processes */
  unsigned long totalhigh; /* Total high memory size */
  unsigned long freehigh;  /* Available high memory size */
  unsigned int mem_unit;   /* Memory unit size in bytes */
  char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};
Community
  • 1
  • 1
Scotty Bauer
  • 1,277
  • 9
  • 14
2

If you want to know the C API,

this question is a possible duplicate of What API do I call to get the system uptime?

If you want to know uptime via shell, use uptime command.

$uptime
Community
  • 1
  • 1
egghese
  • 2,193
  • 16
  • 26