Sleep for exact time in python

前端 未结 7 1479
迷失自我
迷失自我 2020-12-11 17:17

I need to wait for about 25ms in one of my functions. Sometimes this function is called when the processor is occupied with other things and other times it has the processor

7条回答
  •  半阙折子戏
    2020-12-11 17:51

    What system are you on? If you're on Windows you may want to do something like this for exact timing:

    import ctypes
    kernel32 = ctypes.windll.kernel32
    
    # This sets the priority of the process to realtime--the same priority as the mouse pointer.
    kernel32.SetThreadPriority(kernel32.GetCurrentThread(), 31)
    # This creates a timer. This only needs to be done once.
    timer = kernel32.CreateWaitableTimerA(ctypes.c_void_p(), True, ctypes.c_void_p())
    # The kernel measures in 100 nanosecond intervals, so we must multiply .25 by 10000
    delay = ctypes.c_longlong(.25 * 10000)
    kernel32.SetWaitableTimer(timer, ctypes.byref(delay), 0, ctypes.c_void_p(), ctypes.c_void_p(), False)
    kernel32.WaitForSingleObject(timer, 0xffffffff)
    

    This code will pretty much guarentee your process will sleep .25 seconds. Watch out though- you may want to lower the priority to 2 or 3 unless it's absolutely critical that this sleeps for .25 seconds. Certainly don't change the priority too high for a user-end product.

提交回复
热议问题