暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

CLOCK_MONOTONIC和CLOCK_REALTIME的真相

han码录 2019-09-02
3507

    最近回顾代码,想起曾经做的一个功能所遇到的问题,认为有必要进行分享。

    起因源于:当时需要获取设备的启机时间并加匹配。Linux环境下系统库API并没有直接提供设备的启机时间,但提供有:

  • CLOCK_MONOTONIC

  以绝对时间为准,获取的时间为系统启动到现在的时间

  • CLOCK_REALTIME

   相对时间,从1970.1.1到目前的时间

   因此,很容易想到,既然设备时区固定,NTP同步系统时钟之后,要知道启机时间,用当前的时间减去系统运行时间,即能得到系统的启机时间。代码也写的很快。

long os_get_sys_boottime(void)
{
struct timespec uptime;
struct timespec curtime;


clock_gettime(CLOCK_MONOTONIC, &uptime);
clock_gettime(CLOCK_REALTIME, &curtime);


return curtime.tv_sec - uptime.tv_sec;
}

    从逻辑很通的实现,在实际的使用中却偶发匹配不上的情况。逻辑上,只要设备没有重启过,这个启机时间就不应该变化。实际上,打印出来即能发现,并非如此:

  • 嵌入式设备打印

root@:~# ./a.out 
curtime 1567418489 uptime 11260 boot time 1567407229
curtime 1567418492 uptime 11263 boot time 1567407229
curtime 1567418493 uptime 11264 boot time 1567407229
curtime 1567418494 uptime 11264 boot time 1567407230
curtime 1567418495 uptime 11266 boot time 1567407229
curtime 1567418496 uptime 11267 boot time 1567407229
curtime 1567418497 uptime 11268 boot time 1567407229
curtime 1567418497 uptime 11268 boot time 1567407229


  • 虚拟机PC打印

root@han-VirtualBox:test# ./a.out 
curtime 1567419150 uptime 707773 boot time 1566711377
curtime 1567419154 uptime 707778 boot time 1566711376
curtime 1567419155 uptime 707779 boot time 1566711376
curtime 1567419156 uptime 707780 boot time 1566711376
curtime 1567419158 uptime 707782 boot time 1566711376
curtime 1567419160 uptime 707784 boot time 1566711376
curtime 1567419161 uptime 707785 boot time 1566711376
curtime 1567419162 uptime 707786 boot time 1566711376
curtime 1567419164 uptime 707787 boot time 1566711377

很明显可以发现,总是会出现1秒的误差,以秒为单位下,出现了不同步,引发了1秒的计算误差。(实践使用time(NULL)和sysinfo的uptime会出现同样的情况)。

    当需要启机时间作为不变量时,可以使用/proc/stat中的btime,在实际使用中,这个值并不会发生变化。

root@han-VirtualBox:test# cat /proc/stat 
cpu 5916782 6554 835066 63584606 278981 0 52646 0 0 0
cpu0 5916782 6554 835066 63584606 278981 0 52646 0 0 0
intr 35537730 39 219 0 0 0 0 0 0 0 359211 669 9648787 156 0 0 691832 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 62817747
btime 1566711376
processes 3027839
procs_running 3
procs_blocked 0
softirq 93812066 94 21626040 219283 8623706 1535238 0 60826 0 0 61746879


文章转载自han码录,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论