打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
获得系统的uptime
userphoto

2015.06.04

关注

有几种方法:

1. 执行命令 uptime

2. 使用clock_gettime 函数和 sysinfo函数

  1. #include <time.h>    
  2. #include <sys/times.h>    
  3. #include <unistd.h>    
  4. #include <sys/sysinfo.h>  
  5.   
  6. void main(void)    
  7. {    
  8.     struct timespec tp;    
  9.     clock_gettime(CLOCK_MONOTONIC, &tp);    
  10. //  clock_t ticks = times(NULL);    
  11. //  printf("seconds: %d\n", ticks / sysconf(_SC_CLK_TCK));    
  12.     printf("up time: %f\n", tp.tv_sec + (float)tp.tv_nsec/1000000000);    
  13.   
  14.     struct  sysinfo info;  
  15.     sysinfo(&info);  
  16.   
  17.     printf("up time (sysinfo.uptime): %d\n", info.uptime);  
  18. }   


3查看 /proc/uptime

下面看一下结果:

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

下面的代码使用sysinfo来计算系统启动的时间:

  1. #include <sys/sysinfo.h>  
  2. #include <time.h>  
  3.   
  4. int main(void)  
  5. {  
  6.     struct sysinfo info;  
  7.     sysinfo(&info);  
  8.   
  9.     time_t boottime = time(NULL) - info.uptime;  
  10.   
  11.     struct timespec monotime;  
  12.     clock_gettime(CLOCK_MONOTONIC, &monotime);  
  13.       
  14.     time_t curtime = boottime + monotime.tv_sec;  
  15.   
  16.     struct timespec realtime;  
  17.     clock_gettime(CLOCK_REALTIME, &realtime);  
  18.   
  19.     printf("Boot time = %s", ctime(&boottime));  
  20.     printf("Current time = %s", ctime(&curtime));  
  21.     printf("Real Time = %s", ctime(&realtime.tv_sec));  
  22.   
  23.     return 0;  
  24. }  

执行结果:

  1. $ ./a.out   
  2. Boot time = Thu May  1 00:49:23 2014  
  3. Current time = Thu May  1 02:08:17 2014  
  4. Real Time = Thu May  1 02:08:18 2014  



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
C++ 如何得到当前进程所占用的内存呢?
Posix timers clock
linux时间函数
linux下常用的几个时间函数:time,gettimeofday,clock
Lenky个人站点 ? Linux下应用程序内测量时间的各种方法
clock get ns
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服