java中的时间同步 [英] Time synchronization in java
问题描述
在for-loop中,我通过检索和处理车辆信息来控制基于模拟步骤的交通模拟器SUMO。为了确保我的程序在实时模拟(1个模拟步骤= 1秒),我想在处理阶段之后睡眠我的程序,直到下一个时间步骤开始。为了获得更好的结果,我正在根据最初采用的参考时间戳计算时间戳。
Inside a for-loop I'm controlling the simulation-step-based traffic simulator SUMO by retrieving and processing information of vehicles. To make sure that my program simulates in "real-time" (1 simulation-step = 1 second) I want to sleep my program after the processing phase until the next time step begins. To get better results I'm calculating the time stamp based on a initially taken reference time stamp.
循环如下所示:
System.out.println("start of traffic simulation ...");
for (int i = 0; i < stepCount; i++)
{
System.out.println("step: " + i);
// set before timeStamp
beforeTimeStamp = System.currentTimeMillis();
if (firstStep)
{
// get reference timeStamp
referenceTimeStamp = beforeTimeStamp;
firstStep = false;
}
else
{
// get next vehicleVector
vehicleVector = masterControl.traCIclient.simulateStep();
}
// process vehicleVector
// set after timeStamp
afterTimeStamp = System.currentTimeMillis();
processingTime = afterTimeStamp - beforeTimeStamp;
// calculate sleepTime
sleepTime = referenceTimeStamp + ((i + 1) * 1000) - afterTimeStamp;
// sleep for sleepTime ms
Thread.sleep(sleepTime);
}
System.out.println("end of traffic simulation ...");
以下是一些变量的输出:
Here's the output of some variables:
step: 0
beforeTimeStamp 1252317242565
reference time: 1252317242565
processing time: 394
test time: 1252317243565
afterTimeStamp 1252317242959
sleepTime: 606
step: 1
beforeTimeStamp 1252317242961
processing time: 665
test time: 1252317244565
afterTimeStamp 1252317243626
sleepTime: 939 (exspected: 1000 - 665 = 335)
正如您所看到的,睡眠时间仅适用于第一个模拟步骤。我不知道这里可能出现什么问题。有没有人有想法?
As you can see the sleep time is only correct for the first simulation step. I have no clue what might me going wrong here. Does anybody has an idea?
BR,
Markus
推荐答案
为什么不睡觉 1000 - processingTime
?这是你能得到正确答案的最接近的答案。
Why not sleep for 1000 - processingTime
? It would be the closest you can get to a correct answer.
您的解决方案仅适用于第一步,因为它仅适用于第一步。您假设您将在 referenceTime +(步骤* 1000)
的每个步骤开始处理,但您不会考虑开销(线程休眠,打印,垃圾收集) 。
打印出 referenceTimeStamp +((i + 1)* 1000) - beforeTimeStamp
看看我的意思
Your solution only works on the first step because it's only correct for the first step. You assume that you will start your processing for each step at referenceTime + (step * 1000)
, but you are not taking overhead (thread sleeping, prints, garbage collection) into account.
Print out referenceTimeStamp + ((i + 1) * 1000) - beforeTimeStamp
to see what I mean
这篇关于java中的时间同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!