1

I am trying to measure the time between a certain event displayed on the screen and until user responses with a input key in pygame. I hope to make the measurement as accurate as possible.

What is the expected/worst case latency in pygame? And, what are alternatives to read from keyboard faster?

Below is the code I am using right now to read from keyboard and measure the time.

def user_input(maxtime_msec): 
    time_start = time.time() 
    time_elapsed_msec = 0 
    key_press = False
    while (time_elapsed_msec < maxtime_msec) and (not key_press):
        for event in pygame.event.get():
            if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_RETURN):
                key_press = True
            else:
                time.sleep(0.001)  
        time_end = time.time()
        time_elapsed_msec = (time_end - time_start)*1000  
    return time_elapsed_msec
r3t2
  • 85
  • 6
  • 1
    This is a very dicey thing to try. Are you running on Windows? If so, it's a multitasking system where your program must share CPU time with other programs. Is the keyboard connected wirelessly or by USB? In that case there will be overhead associated with that. For these reasons, people who write real-time systems (like me) can't use Windows (or pretty much any modern OS) directly, but usually need specialized hardware. Offhand your code looks about as good as you can get. – Paul Cornelius Feb 06 '16 at 01:05
  • I am using Ubuntu. I am currently running this on my laptop but eventually this will be ran on OSX. May I ask what specialized hardware you use? – lavenderLatte Feb 06 '16 at 01:38
  • My company's hardware is for lasers, not for games. But the timing issue applies across the board. Neither Windows nor Ubuntu is a hard real-time OS. If you want exact timing you need to take into account all sorts of issues. My advice is to try the simple approach, as you have done already, and see if it works well enough.for you. Be aware that it won't be perfect. – Paul Cornelius Feb 06 '16 at 02:52
  • You should be aware that sleep resolution will be a problem as well http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep – pyInTheSky Feb 06 '16 at 07:07
  • You will want to use the timeit module to measure the execution speed of your loop. You need to consider screen draw/refresh rates as well. – pyInTheSky Feb 06 '16 at 07:11

0 Answers0