Reputation: 882
I'm making a game in Python and I need to find how long it takes for a user to enter their response to a prompt. I would then like to have the input stored in a variable.
I have already tried using the timeit
module with no success:
import timeit
def get_input_from_user():
variable = input("Prompt: ")
time_to_respond = timeit.timeit(get_input_from_user())
This code gives the following 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
Is there another way of going about this? Thank you!
Upvotes: 0
Views: 717
Reputation: 51405
Using timeit
, you can check how much time an expression takes using:
time_to_respond = timeit.timeit(get_input_from_user, number=1)
Note, no parentheses, and the argument number=1
, to make sure that it only gets called once.
For example, this could return:
>>> time_to_respond
1.66159096399997
But since you want access to both the variable and the time to respond, I would suggest doing something along these lines instead, using the time
module:
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!'
Upvotes: 3