我如何计算用户输入输入的时间?

How do I time how long a user takes to type input?

我正在 Python 制作游戏,我需要了解用户输入对提示的响应需要多长时间。然后我想将输入存储在一个变量中。

我已经尝试使用 timeit 模块但没有成功:

import timeit
def get_input_from_user():
    variable = input("Prompt: ")
time_to_respond = timeit.timeit(get_input_from_user())

此代码给出以下内容ValueError

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 232, in timeit
    return Timer(stmt, setup, timer, globals).timeit(number)
  File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\timeit.py", line 128, in __init__
    raise ValueError("stmt is neither a string nor callable")
ValueError: stmt is neither a string nor callable

还有其他方法吗?谢谢!

使用 timeit,您可以使用以下方法检查表达式花费的时间:

time_to_respond = timeit.timeit(get_input_from_user, number=1)

注意,没有括号和参数 number=1,以确保它只被调用一次。

例如,这可以 return:

>>> time_to_respond
1.66159096399997

但是由于您想要访问变量和响应时间,我建议您改为使用 time 模块按照这些思路做一些事情:

import time
def get_input_from_user():
    s = time.time()
    variable = input("Prompt: ")
    e = time.time()
    return e-s, variable

time_to_respond, variable = get_input_from_user()

>>> time_to_respond
2.4452149868011475
>>> variable
'hello!'