python3时间结果不正确

时间:2017-02-08 03:04:16

标签: python-3.x time

我收到了以下代码。我已经添加了time()来让我计算用户遇到问题和用户输入数据之间的延迟。

但结果时间并不总是正确的,我不确定原因。

from time import time
from random import randint

a = randint(0,1000)
b = randint(0,1000)
cor_answer = a+b
usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))

start = time()
if usr_answer == cor_answer:
    print("yes you are correct!")
else:
    print("no you are wrong!")
end = time()

elapsed = end - start

print("That took you "+str(elapsed)+" seconds. \n")

这是从cmdline执行的结果:

~/math_quiz/math_quiz$ python3 math_quiz.py 
what is 666+618? 
1284
1284
1284
yes you are correct!
That took you 4.291534423828125e-05 seconds. 

但是time()显然有效,因为如果我在IDLE中运行它,我会得到这个:

>>> start = time()
>>> time()-start
13.856008052825928

所以我不确定为什么cmdline的执行会给我带来不同的结果。

由于

1 个答案:

答案 0 :(得分:-1)

您的代码当前在用户输入答案后启动计时器

您需要在start = time()

之前添加此代码usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))