'What is the most precise delay/sleep function in python

I was making an auto-clicker which has a cps of about 1500, to tune the cps to about 100-1200 cps I need a delay of accuracy about 1ms. Through my experimentation with the time library got me an accuracy of about 15ms-20ms which brings the cps up to 63 only.

This is the click function

def thread():
    while run:
        if keyboard.is_pressed("c"):
            x, y = pyautogui.position()
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
        time.sleep(delay)

And this is the cps tester function

def print_cps():
    state_left = win32api.GetKeyState(0x01)
    while run:
        total = 0
        prev = time.time()

        while (time.time() - prev) < 0.5:
            a = win32api.GetKeyState(0x01)
            if a != state_left:  # Button state changed
                state_left = a
                if a < 0:
                    total += 1
        out = "\rAverage CPS: " + str(total/(time.time()-prev))
        sys.stdout.write(out)


Solution 1:[1]

You could try to use time.sleep() function for this. Then you won't need to use any loops.

Refer to this: https://www.programiz.com/python-programming/time/sleep

Solution 2:[2]

6month ago but it's top of "python accurate sleep" search result.

use time.perf_counter() instead of time.time().

returns like time.time() but 100ns accuracy(windows)

I got at least 0.0000002 =200ns accuracy. see below:

https://peps.python.org/pep-0564/#annex-clocks-resolution-in-python

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gedas Miksenas
Solution 2 magicbox