'Python measure time between key presses and time between a key press and key release

I'm trying to measure time between key presses and time between a key press and key release. This is the code I have so far:

import pynput
from pynput.keyboard import Key, Listener
import time
import threading
key_pressed_twice = True
key_is_pressed = False
startPressed = time.time()

key_pressed_list = []
key_released_list = []

def on_press(key):
    global key_is_pressed
    global startRelease
    global key_pressed_twice
    global startPressed

    key_pressed_twice = not key_pressed_twice
    if(key_pressed_twice):
        endPressed = time.time()
        miliSeconds = '%.1f' % ((endPressed-startPressed)*1000) 
        #writeToFile(miliSeconds,"pressed.txt")
        key_pressed_list.append(miliSeconds + ", ")
        startPressed = time.time()
    if key_is_pressed == False:
        startRelease = time.time()
        key_is_pressed = True

def on_release(key):
    global key_is_pressed
    global endRelease
    global startRelease
    key_is_pressed = False
    endRelease = time.time()
    miliSeconds = '%.1f' % ((endRelease-startRelease)*1000) 
    print(miliSeconds)
    key_released_list.append(miliSeconds + ", ")
    if key == Key.esc:
        writeToFile(key_released_list,"release.txt")
        writeToFile(key_pressed_list,"pressed.txt")
        return False

def writeToFile(tempList,filename):
    with open(filename, "a") as file:
        file.write("".join(tempList))


with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

The problem I'm having is that the time between key presses seems way off. If I'm hammering the key I'm getting a delay of around 300 ms. This seems way to long since I'm spamming the key. So anyone got an idea of what might be wrong?

EDIT: Reduce file input, timing still seems off.



Solution 1:[1]

I think you should declare something like time_last_key_pressed and compute the time between key presses by comparing the time when the new press occurred with the time stamp from the last press. Overall it would look like this:

def on_key_press(key): #what to do on key-press
    global time_key_pressed
    global time_last_key_pressed
    time_key_pressed = time_in_millis()
    if time_last_key_pressed is not None:
        print("DD time", time_key_pressed - time_last_key_pressed, "miliseconds")
        downDownTime.append(time_key_pressed - time_last_key_pressed)
    
    time_last_key_pressed = time_key_pressed

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 Jack