System.currentTimeMillis vs System.nanoTime

后端 未结 10 1247
后悔当初
后悔当初 2020-11-21 22:56

Accuracy Vs. Precision

What I would like to know is whether I should use System.currentTimeMillis() or System.nanoTime()<

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 23:11

    For game graphics & smooth position updates, use System.nanoTime() rather than System.currentTimeMillis(). I switched from currentTimeMillis() to nanoTime() in a game and got a major visual improvement in smoothness of motion.

    While one millisecond may seem as though it should already be precise, visually it is not. The factors nanoTime() can improve include:

    • accurate pixel positioning below wall-clock resolution
    • ability to anti-alias between pixels, if you want
    • Windows wall-clock inaccuracy
    • clock jitter (inconsistency of when wall-clock actually ticks forward)

    As other answers suggest, nanoTime does have a performance cost if called repeatedly -- it would be best to call it just once per frame, and use the same value to calculate the entire frame.

提交回复
热议问题