python 中的 sleep() 是否足够准确? [英] is sleep() accurate enough in python?

查看:46
本文介绍了python 中的 sleep() 是否足够准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 python 脚本来记录 PC 全天的正常运行时间,并在第二天将使用情况存储在数据库中.

I have created a python script that records the up-time of PC throughout the day, and stores the usage in a database the next day.

while 1:
        time.sleep(59.9)
        # now some code that increments the up-time value by 1 minute
        # my other code here

这是时间加法器函数的蓝图,它停止执行 59.9 秒(我选择了 59.9 秒而不是 1 分钟,因为增量值需要写入 2 个单独的文件,所以我想给出大约 100 毫秒的时间以便及时完成这些操作),然后将增加的值写入两个单独的文件,并继续这样做直到系统关闭.(这个循环的每一次迭代都意味着一分钟过去了)

This is the blueprint of the time adder function which halts the execution for 59.9s (I chose 59.9s instead of 1 minute, as the incremented value needs to be written to 2 separate files, so i wanted to give about 100ms of time in order for the completion of those operations in time) and then writes the incremented value to two separate files, and continues to do so until the system is turned off. (every single iteration of this loop will signify that a minute has passed by )

我之所以选择 sleep() 而不是其他一些经过/存储时间的方式,是因为它在电源浪涌的情况下可以很好地应对,因为增加了正常运行时间每分钟写一次.

The reason why I went for sleep() instead of some other way of elapsing/storing time, is because it counters fairly well in case of power surge's, as the incremented up-time is being written every minute.

我知道 time.sleep() 函数在暂停一段微妙的持续时间(以毫秒或微秒为单位)时不是一个精确和准确的函数.但是因为在我的代码中时间被暂停了大约一分钟,所以我相信睡眠功能的偏差/不准确度不会很大.

I know that the time.sleep() function is not a precise and accurate one when it comes to halting time for a subtle duration (in milliseconds or microseconds). But since in my code the time is being halted for approximately a minute, so I believe that the deviation/inaccuracy of the sleep function won't be considerable.

我对上述脚本进行了大约 2 个月的测试,结果相当不错.

I have tested the above script for about 2 months and the results are quite favourable.

所以我想知道这是否是一种存储正常运行时间的有效方法,或者是否存在更好的方法.

So I was wondering whether it is an efficient way of storing up-time, or there exists a better way of doing so.

推荐答案

你可以试试 GetTickCount64 函数.

示例:

import ctypes
import datetime


def uptime_in_ms():
    lib = ctypes.windll.kernel32
    return lib.GetTickCount64()

def frmt(dt):
    d = dt.days
    _s = dt.seconds
    h, rem = divmod(_s, 3600)
    m, s = divmod(rem, 60)
    return f'{d} day(s), {h:02}h:{m:02}m:{s:02}s'

if __name__ == '__main__':
    ms = uptime_in_ms()
    dt = datetime.timedelta(milliseconds=ms)
    uptime = frmt(dt)
    print(uptime)

测试:

C:\Users\User>python Desktop/get_uptime.py
1 day(s), 00h:18m:51s

注意事项:

  1. 最低支持的客户端 - Windows Vista
  2. 这只是一个例子,所以没有验证这个库是否存在
  3. 此示例使用 f 字符串格式 - Python 3.6+

这篇关于python 中的 sleep() 是否足够准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆