TOC

/proc/uptime 在开发中的一点应用

在一些和时间关联紧密的操作中,可要提防修改时间对系统运行的影响,这个时候 /proc/uptime 就派上用场了。

/proc/uptime 是个啥?

执行与分析

$ cat /proc/uptime
796.02 2524.34

得到的两个结果中,前者就是系统开机时间,后者是系统开机之后的累计空闲时间,都是以秒为单位。
而且都是保留两位小数,那么就是说,它们的时间精度都是 10 毫秒。

为什么看起来空闲时间比开机时间都还多好多?因为那是多个核心的空闲时间累计值,当然比较多。
我的电脑是四个核心,那么总的 CPU 空闲比例应该是 2514.34 / (796.02 * 4),大约是 79%,也还行吧。

参考资料(man proc

/proc/uptime
        This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).

此外,GNU/Linux 中一般还有一个 uptime 的命令,估计关于启动时间的部分,还是来自 /proc/uptime 文件。

应用

我面临的场景:一个根据系统时间做消息推送的长轮询机制,结果 Web 服务器系统时间突然被修改了,会不会推送了过时信息,或者漏掉一部分信息不推送?
解决方案:和前端通讯时,作时间标记的值,换成 uptime,而不是 UNIX 时间戳。

def uptime():
    " 系统开机时间,时间精度为 ms "
    with open('/proc/uptime', 'r') as f:
        s = f.read()
        return int(s[:s.index(' ')].replace('.', '')) * 10