Get the uptime of the system

Source: Internet
Author: User
Tags current time

There are several ways:

1. Execute command uptime

2. Using the Clock_gettime function and the SysInfo function

#include <time.h>
#include <sys/times.h>
#include <unistd.h>
#include <sys/  sysinfo.h>

void Main (void)
{
struct TIMESPEC tp;  
clock_gettime (Clock_monotonic, &TP);  
//clock_t ticks = times (NULL);  
//printf ("Seconds:%d\n", ticks/sysconf (_SC_CLK_TCK));  
printf ("Up Time:%f\n", Tp.tv_sec + (float) tp.tv_nsec/1000000000);    

struct SysInfo info;
SysInfo (&info);

printf ("Up Time (sysinfo.uptime):%d\n", info.uptime);
} 



3 views/proc/uptime

Here's a look at the results:

$./a.out;uptime;cat/proc/uptime up
time:4581.407706
-Time (sysinfo.uptime): 4582
 02:05:45 up  1:16 ,  3 users,  load average:0.08, 0.45, 0.95
4581.41 14391.24

The following code uses SysInfo to calculate when the system starts:

#include <sys/sysinfo.h>
#include <time.h>

int main (void)
{
	struct sysinfo info;
	SysInfo (&info);

	time_t boottime = Time (NULL)-info.uptime;

	struct Timespec monotime;
	Clock_gettime (Clock_monotonic, &monotime);
	
	time_t curtime = Boottime + monotime.tv_sec;

	struct Timespec realtime;
	Clock_gettime (Clock_realtime, &realtime);

	printf ("Boot time =%s", CTime (&boottime));
	printf ("Current time =%s", CTime (&curtime));
	printf ("Real time =%s", CTime (&realtime.tv_sec));

	return 0;
}

Execution Result:

$./a.out 
Boot time = Thu  1 00:49:23 Current time
= Thu  1 02:08:17
Real time = Thu M AY  1 02:08:18 2014



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.