I'm trying make a python program initiating a nanosecond count when a key on the keyboard is pressed, stopping it when the key is released and calculating how long the key was pressed down for.
So far I have tried several different structures using the modules pynput and time. I release the code below is wrong, but I'm adding it anyway, so somebody could potentially pinpoint me in the right direction.
When I run the code below it does print a time in nanoseconds. However, the time printed keeps increasing for every key I try, no matter for how long I press the key down. It seems the method: time.perf_counter_ns() does not stop counting even when the function block is finished and called again after that.
import pynput, time
from pynput.keyboard import Key,Listener
timer = 0
timer2 = 0
def press(Key):
timer = time.perf_counter_ns()
def release(Key):
timer2 = time.perf_counter_ns()
print(timer-timer2)
with Listener(on_press=press, on_release=release) as listener:
listener.join()
print(timer)inrelease()and you'll see it's always0. Also your arithmetic results in a negative number: you should reverse the operands.