Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring time between keystrokes in python

Tags:

python

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.

like image 235
Nico Bellic Avatar asked Oct 14 '25 14:10

Nico Bellic


2 Answers

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.

like image 161
ben w Avatar answered Oct 17 '25 04:10

ben w


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
like image 39
Raghav Malik Avatar answered Oct 17 '25 03:10

Raghav Malik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!