linux从系统启动到当前时刻的时间

方法1

#include <time.h>

int clock_gettime(clockid_t clk_id, struct timespec* tp);

可以根据需要,获取不同要求的精确时间

参数

clk_id : 检索和设置的clk_id指定的时钟时间。
CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,
中间时刻如果系统时间被用户改成其他,则对应的时间相应改变
  CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响,不记录休眠时间
  CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
  CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
struct timespec
{
        time_t tv_sec; /* 秒*/
        long tv_nsec; /* 纳秒*/
};

这一种可以改成和window下GetTickCount()函数类似的功能,GetTickCount()返回值是unsigned long型,满49天多会达到最大值重新从0计时,做服务器时需要注意。

方法2

#include <sys/sysinfo.h>

int sysinfo(struct sysinfo *info);

  1. struct sysinfo {  
  2.       long uptime;          /* 启动到现在经过的时间 */  
  3.       unsigned long loads[3];    
  4.       /* 1, 5, and 15 minute load averages */  
  5.       unsigned long totalram;  /* 总的可用的内存大小 */  
  6.       unsigned long freeram;   /* 还未被使用的内存大小 */  
  7.       unsigned long sharedram; /* 共享的存储器的大小*/  
  8.       unsigned long bufferram; /* 共享的存储器的大小 */  
  9.       unsigned long totalswap; /* 交换区大小 */  
  10.       unsigned long freeswap;  /* 还可用的交换区大小 */  
  11.       unsigned short procs;    /* 当前进程数目 */  
  12.       unsigned long totalhigh; /* 总的高内存大小 */  
  13.       unsigned long freehigh;  /* 可用的高内存大小 */  
  14.       unsigned int mem_unit;   /* 以字节为单位的内存大小 */  
  15.       char _f[20-2*sizeof(long)-sizeof(int)];   
  16.       /* libc5的补丁  
  17. };  
 

 

 

posted @ 2021-02-28 01:44  KwinWei  阅读(387)  评论(0编辑  收藏  举报