3
我需要爲小遊戲實現毫秒精度計時器。哪種方法最適合這個?我目前的做法是使用System.currentTimeMillis()。它似乎工作得不錯,但也許有一些我不知道的陷阱。標準的計時方法是什麼?Android簡單計時問題
我需要爲小遊戲實現毫秒精度計時器。哪種方法最適合這個?我目前的做法是使用System.currentTimeMillis()。它似乎工作得不錯,但也許有一些我不知道的陷阱。標準的計時方法是什麼?Android簡單計時問題
你的計時器只會和你的系統一樣好。它根本不會比這更好。作爲一名前職業遊戲開發者(並且仍然在做副作用),我建議不要超過毫秒級的精度要求。你可能不需要它。
用此程序確定您的時鐘精度:
/*
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");
}
}
好像很多事情可能會影響程序的輸出如上下文切換。我認爲你沒有對'currentTimeMillis'準確度施加太大的壓力是正確的。 – 2011-03-25 21:19:44
@Matthew,你說的沒錯。當然,當我運行它很多次(數百次)時,我會得到一致的16或17,從不變化。你提出了我試圖做的確切的觀點:不要依賴'currentTimeMillis'的準確性。 – corsiKa 2011-03-25 22:04:55
感謝您的數據。知道這很有趣! – 2011-03-25 22:06:09