我正在尝试编写一个我需要接受按键的应用程序,并在用户停止输入时调用函数(或者当按键之间有指定的延迟时)。
如何测量两次击键之间的时间?
答案 0 :(得分:8)
这样的事情:
NSDate *start = [NSDate date];
// do the thing you are timing
NSDate *stop = [NSDate date];
NSTimeInterval duration = [start timeIntervalSinceDate:stop];
答案 1 :(得分:5)
可能更好的方法是获取与每个按键相关联的NSEvent,并比较它们的-timestamp属性的差异。
答案 2 :(得分:2)
获取当前时间,然后减去上一个当前时间。请参阅-[NSDate timeIntervalSinceDate:]。
答案 3 :(得分:0)
如果很容易在计时器上重置超时,那么不确定计算密集程度如何。
答案 4 :(得分:0)
我认为您应该为此使用线程。为按键创建线程,并且您可以在每个线程中计算两次按键之间的时间。有关更多说明,请观看我的视频以获取确切的解决方案。
https://www.youtube.com/watch?v=sDGYM8LeZh8
请参见下面的代码:
import keyboard # keyboard library
import string # string for capturing keyboard key codes
import time # for capturing time
from threading import * # threads for keypresses
# get the keys
keys = list(string.ascii_lowercase)
# key listener
def listen(key):
while True:
global timeda # global variable for storing time for 1st keypress
global newda # global variable for storing time for next keypress
keyboard.wait(key) # when key is presses
# check if variables are defined
try:
timeda
newda
# this will run for the first keypress only so assign initial time to variable
except NameError:
timeda = time.time()
newda = time.time()
print("First key is pressed at "+str(round(newda,2)))
print('\n==========\n')
# for all keypresses except for the first will record time here
else:
newda = time.time() # assign time for next keypressed
newtime = newda - timeda # get difference between two keys presses
# just to test time of first keypress
print("Previous keypress was at "+str(round(timeda,2)))
# just to test time of next keypress
print("Current keypress is at "+ str(round(newda,2)))
# convert time into seconds
newtime = newtime % 60
print("Difference between two keypresses is "+str(round(newtime,2)))
print('\n==========\n') # need some space for printing difference
timeda = time.time()
# creating threads for keys and assigning event and args
threads = [Thread(target=listen, kwargs={'key':key}) for key in keys]
# calling each thread
for thread in threads:
thread.start()
# thats it