Android简单时序问题

cam*_*ace 3 android timing

我需要为小游戏实现毫秒精确的计时器.哪种方法最合适呢?我目前的方法是使用System.currentTimeMillis().它似乎工作得很好,但也许有一些我不知道的陷阱.什么是计时的标准方法?

cor*_*iKa 8

您的计时器只会与您的系统实现它一样好.它根本不会比那更好.

作为一名前职业游戏开发人员(并且仍在做侧面项目),我建议不要达到毫秒精度要求.你可能不需要它.

使用此程序确定您的时钟准确度:

/*
C:\junk>javac TimerTest.java

C:\junk>java TimerTest
Your delay is : 16 millis

C:\junk>
*/
class TimerTest {

    public static void main(String[] args) {
        long then = System.currentTimeMillis();
        long now = then;
            // this loop just spins until the time changes.
            // when it changes, we will see how accurate it is
        while((now = System.currentTimeMillis()) == then); // busy wait
        System.out.println("Your delay is : " + (now-then) + " millis");

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:在Android上,你最好使用System.nanoTime().不是因为纳秒级分辨率,而是因为它基于单调时钟.如果运营商推送时间更新,则currentTimeMillis的值可以向前或向后跳转,如果您使用此延迟,可能会导致游戏暂停.(FWIW,我使用nanoTime()从上面的测试中获得了更精细的结果.) (2认同)