Does the method System.currentTimeMillis() really return the current time?

為{幸葍}努か 提交于 2019-12-20 14:19:12

问题


Based on ideas presented in link I implemented several different "sleep methods". One of this methods was the "binary sleep", which looks like this:

while (System.currentTimeMillis() < nextTimeStamp)
{
sleepTime -= (sleepTime / 2);
sleep(sleepTime);
}

Because the check if the next time step is already reached takes place at the beginning I, would expect that the method is running too long. But the cummulative distribution of the simulation error (expected time - real time) looks like this: alt text http://img267.imageshack.us/img267/4224/errorvscummulativearran.jpg

Does somebody has an idea why I'm getting this results? Maybe the method System.currentTimeMillis() does not really return the current time?

BR,

Markus

@irreputable

When I made the evaluation I also created a bell curve by using a german statistic program. Because it was not possible to change caption, here is the english translation of all relevant items:

Häufigkeit = frequency

Fehler = error

Mittelwert = average

Std-Abw = standard deviation

alt text http://img694.imageshack.us/img694/2254/bellcurve.jpg


回答1:


No it does not. Its young brother System#nanoTime() has a much better precision than System#currentTimeMillis().

Apart from the answers in their Javadocs (click at the links here above), this subject was discussed several times here as well. Do a search on "currenttimemillis vs nanotime" and you'll get under each this topic: System.currentTimeMillis vs System.nanoTime.




回答2:


Per the docs,

 * Returns the current time in milliseconds.  Note that
 * while the unit of time of the return value is a millisecond,
 * the granularity of the value depends on the underlying
 * operating system and may be larger.  For example, many
 * operating systems measure time in units of tens of
 * milliseconds.



回答3:


What you are seeing is the underlying clock resolving to 15ms resolution. This is a feature of the OS & interrupt rate. There is a patch for the linux kernel to increase this resolution to 1ms, I'm not sure about windows. There have been a number of posts about this already.



来源:https://stackoverflow.com/questions/1902368/does-the-method-system-currenttimemillis-really-return-the-current-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!