有几种方法:
1. 执行命令 uptime
2. 使用clock_gettime 函数和 sysinfo函数
#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查看 /proc/uptime
下面看一下结果:
$ ./a.out;uptime;cat /proc/uptime
up time: 4581.407706
up time (sysinfo.uptime): 4582
02:05:45 up 1:16, 3 users, load average: 0.08, 0.45, 0.95
4581.41 14391.24
下面的代码使用sysinfo来计算系统启动的时间:
#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;
}
执行结果:
$ ./a.out
Boot time = Thu May 1 00:49:23 2014
Current time = Thu May 1 02:08:17 2014
Real Time = Thu May 1 02:08:18 2014