如何模拟以纳秒为单位的计数并在设定的时间执行命令?

问题描述 投票:0回答:1

我正在模拟一个数学悖论,想用Python来演示数学。我想以纳秒为单位进行计数,在某些点执行计算。但我不知道如何让计数器工作。

这是我成功实现的一个以秒为单位的版本。

achilles_speed = 10 #------------Achilles travels at 10 meteres per second
tortoise_speed = 0.1 #------------Achilles travels at 0.1 meteres per second
clock = 0  #----------clock start position
end = 11 #-------Measuring this run will follow a zeroth iteration on time, because Achilles cannot cover any distance in 0 seconds. Therefore, we want use 11 as our end time

while clock < end:
   distance_a = achilles_speed*clock
   print(f'In {clock} seconds, Achilles has covered {distance_a} meters')`
   distance_t = round(tortoise_speed*clock, 2)
   print(f'In {clock} seconds, the Tortoise has covered {distance_t} meters')
   print('************************************')
   clock+=1 

if distance_a > distance_t:
   print('ACHILLES WINS!')
else:
   print('THE TORTOISE WINS!')'

我想以纳秒为单位进行计数,并在到达特定点时执行一些命令。

上面的代码有效,但如果有更好的纳秒计数,我完全愿意接受全新的方法。

python time counter
1个回答
0
投票

您正在使用计数器跟踪经过的时间,但我认为您确实想使用代表实际经过时间的适当浮点来跟踪它。注意

time.time()
不是高分辨率
time.perf_counter()

import time

location_template = "In {elapsed_time} seconds, Achilles has covered {achilles_distance} meters while the tortise {tortoise_distance} meters"
achilles_speed_mps = 10
tortoise_speed_mps = 0.1
total_time = 10

start_time = time.time()
elapsed_time = 0
while elapsed_time <= total_time:
   achilles_distance = elapsed_time * achilles_speed_mps
   tortoise_distance = elapsed_time * tortoise_speed_mps
   location_report = location_template.format(
        elapsed_time=round(elapsed_time, 3),
        achilles_distance=round(achilles_distance, 2),
        tortoise_distance=round(tortoise_distance, 2),
   )
   print(location_report, end="\r", flush=True)
   elapsed_time = time.time() - start_time

winner = "ACHILLES" if achilles_distance > tortoise_distance else "THE TORTOISE"
print(f'\n{winner} WINS!')
© www.soinside.com 2019 - 2024. All rights reserved.