我用来执行代码的秒表在没有明显原因的情况下四舍五入到一个有效数字。
FormTime
是从FORM
手动定义的
我已经从FORM=[[1, 1, 0, 0, 0],
中删除了它,以包括调试目的的时间
FORM=[[1], [1.875], [2.25], [4.562], [5.438]]
stopwatch
定义如下;
import datetime
from math import floor
a = datetime.datetime.now()
while True:
b = datetime.datetime.now()
c = (b - a)
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
...
stopwatch
running in loop输出;
>>> stopwatch
0.0
...
0.123
...
0.2
例如,这里是执行时间(FormTime
)与实际执行时间(Ex
,即stopwatch
)
count = 0
a = datetime.datetime.now()
while True:
b = datetime.datetime.now()
c = (b - a)
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
if FORM[count][0]<=stopwatch:
print(f'FormTime = {FORM[count][0]}', end="")
print(f'{" "*int(7-len(str(FORM[count][0])))}', end="") #Just decorative spacing in terminal
print(f'Ex ≈ {stopwatch}') #Ex = Executed @
count+=1
返回;
FormTime = 1 Ex ≈ 1.0
FormTime = 1.875 Ex ≈ 1.9
FormTime = 2.25 Ex ≈ 2.3
FormTime = 4.562 Ex ≈ 4.6
FormTime = 5.438 Ex ≈ 5.5
知道为什么当stopwatch
=一个有效数字时执行吗?
为什么是四舍五入?
- 不要介意
Exception has occurred: IndexError list index out of range, line 21
这是打算在演示结束时发生的
roundMicro = floor(c.microseconds/1e3)
stopwatch = float(str(c.seconds)+'.'+str(roundMicro))
这两行可能不是你想要的。假设c.microseconds == 3000
,你会得到roundMicro = 3
,最终得到1.3
,而它应该是1.003
。
stopwatch = "{:.3f}".format(c.seconds + c.microseconds * 1e-6)
# => 1.003
如果您需要将截断的值转换为数字,您仍然可以调用float(stopwatch)
来转换字符串。