is sleep() accurate enough in python?

2019-08-19 06:48发布

问题:

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

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 )

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.

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.

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.

回答1:

You can try GetTickCount64 function.

Exmaple:

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)

Testing:

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

Notes:

  1. Minimum supported client - Windows Vista
  2. This is just an example so there is no validation if this library exists
  3. This example is using f-string formatting - Python 3.6+