4

Using the following code:

   >>> import time
   >>> start = time.time()
   >>> end = time.time()
   >>> end - start

one can measure time between "start" and "end". What about measuring the time between specific keystrokes? Specifically, if a module was run and the user started typing something, how can python measure the time between the first keystroke and the enter key. Say I ran this script and it said: "Please enter your name, then press enter: ". I write Nico, and then press enter. How can I measure time between "N" and the enter key. This should be in seconds, and after pressing enter, the script should end.

Nico Bellic
  • 363
  • 2
  • 4
  • 13
  • 1
    This depends on *how* you actually get input from the user. If you're using Python's built-in `input()` (or `raw_input()`), you can't get at the individual keystrokes. If you're using [pygame](http://pygame.org) (for example), you can. – Greg Hewgill Feb 03 '12 at 18:57
  • 1
    Related: http://stackoverflow.com/q/694296/535275 – Scott Hunter Feb 03 '12 at 18:59
  • @FGhilardi Actually, a friend showed me this (he didn't know how to do it), and I got really curious myself. No, not homework. – Nico Bellic Feb 03 '12 at 19:07

3 Answers3

3

This will work (on some systems!):

import termios, sys, time
def getch(inp=sys.stdin):
    old = termios.tcgetattr(inp)
    new = old[:]
    new[-1] = old[-1][:]
    new[3] &= ~(termios.ECHO | termios.ICANON)
    new[-1][termios.VMIN] = 1
    try:
        termios.tcsetattr(inp, termios.TCSANOW, new)
        return inp.read(1)
    finally:
        termios.tcsetattr(inp, termios.TCSANOW, old)


inputstr = ''
while '\n' not in inputstr:
    c = getch()
    if not inputstr: t = time.time()
    inputstr += c
elapsed = time.time() - t

See this answer for nonblocking console input on other systems.

Community
  • 1
  • 1
ben w
  • 2,490
  • 14
  • 19
1

A simple way you could do that is:

from time import time
begin = time.time()
raw_input() #this is when you start typing
#this would be after you hit enter
end = time.time()
elapsed = end - begin
print elapsed
#it will tell you how long it took you to type your name
Raghav Malik
  • 751
  • 1
  • 6
  • 20
0

On Windows you can you msvcrt.kbhit() to tell when a key has been pressed. See http://effbot.org/librarybook/msvcrt.htm for a worked-out example.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485