2012-02-03 45 views
3

使用以下代码:测量击键之间的时间在python

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

可以测量之间的“开始”和“结束”的时间。衡量特定击键之间的时间怎么样?具体来说,如果一个模块运行并且用户开始输入内容,python如何测量第一个按键和输入密钥之间的时间。说我跑这个脚本,它说:“请输入你的名字,然后按回车:”。我写Nico,然后按回车。我如何测量“N”和回车键之间的时间?这应该是在几秒钟内,并按下输入后,脚本应该结束。

+0

功课?还是好奇? – FGhilardi 2012-02-03 18:55:06

+1

这取决于*你实际上得到了用户的输入。如果你正在使用Python的内建'input()'(或'raw_input()'),你就无法获得单独的按键。如果你使用[pygame](http://pygame.org)(例如),你可以。 – 2012-02-03 18:57:06

+1

相关:http://stackoverflow.com/q/694296/535275 – 2012-02-03 18:59:20

回答

2

这将工作(在某些系统!):

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 

对其他系统的非阻塞控制台输入见this answer

1

你能做到这一点的简单方法是:

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