Should System.nanoTime() in Java be explicitly casted to a double for game loop?

时间:2015-07-24 10:13:50

标签: java game-loop

I am writing a game loop in Java and trying to calculator deltas. When attempting to get the current time, the following does not give me an error in my IDE. However the function returning a double, where are System.nanoTime() return a long. Why is this not an error?

private static double getTime() {
    return System.nanoTime() / 1000000000;
}

Is explicitly casting to a double better?

private static double getTime() {
    return (double) System.nanoTime() / (double) 1000000000;
}

1 个答案:

答案 0 :(得分:2)

In the first function, the division will be integer division and the result of the division will be casted to double. It is thus equivalent of return (double)(System.nanoTime() / 1000000000);

So for example if the System.nanoTime() gives a value of 142154, the getTime() will return 0, because in integer division the fractions are ignored. 142154 / 1000000000 returns a value of 0.000142154 which will thus be rounded to zero.

The second function will on the otherhand perform an floating-point division, which will keep the fractions and thus be more precise. You don't have to cast both of the arguments to double, only one of them.

The reason the first version of getTime() will not give an error is that Java implicitly casts long to double because double is more precise data type than long. For the same reason int can be implicitly casted to long (but not other way around!).