我有一个棘手的问题要解决。 我在方法调用之前和之后立即使用 System.currentTimeMillis() 因为 我必须测量这两个语句之间耗时。
waitingTime = System.currentTimeMillis(); //starts calculating time
bridge.getIn(direction); // tries to enter the bridge
waitingTime = System.currentTimeMillis() - waitingTime ;// time elapsed
我担心的是每次运行程序时都会得到不同的结果。
我明白了(这是完美的):
Generated cars going north: 0
Generated cars going south: 2
Waiting time for every single car:
==============================================================
A0/South:109ms
A1/South:0ms
==============================================================
Mean waiting time southbound cars : 54ms
然后几秒钟后我再次运行程序,我得到(这是错误的):
Generated cars going north: 0
Generated cars going south: 2
Waiting time for every single car:
==============================================================
A0/South:0ms
A1/South:94ms
==============================================================
Mean waiting time southbound cars : 47ms
我说这个输出是错误的,因为每辆车的等待时间绝不能少于 100 毫秒。
什么会实际影响基于 currentTimeMillis 函数的时间计算?
为什么我得到不同的结果?
有人可能会疑惑:每次的输入都是一样的吗?我会说是的..输入参数
始终相同(两个示例)但程序使用 Random 类生成一个
给定的线程数。
那是罪魁祸首吗?
程序的一些细节:
一群汽车从北向南(反之亦然)沿着双车道行驶。 过了一会儿,他们到达一座桥。这座桥只有一条路,容量有限。 汽车通过这座桥需要 100 毫秒。不允许交通碰撞。
非常感谢。
最佳答案
输出/结果没有错。操作系统暂时中断当前正在执行的程序,运行一个高优先级的程序,还有其他因素。因此时间滞后。如果你想检查程序执行的准确时间,请尝试 System.nanoTime()
它以纳秒为单位返回时间并运行 N 次并取次数的平均值(即便如此我无法向您保证执行时间将保持不变)
我的意思是尝试一些如下所示的事情。
long totalTime=0;
for(i=0;i<n;i++){ //where n is some value say 3,4,5
waitingTime = System.nanoTime(); //starts calculating time
bridge.getIn(direction); // tries to enter the bridge
waitingTime = System.nanoTime() - waitingTime ;// time elapsed
totalTime+=waitingTime;
}
long totalTimeInMillis = totalTime/(n*1000);
注意:确保每次执行的环境都应保持相同。
关于java - 相同输入不同输出..时间计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11187689/