Dec 6, 2011

Java時間解析度

Inside the Hotspot VM: Clocks, Timers and Scheduling Events - Part I - Windows 說明作業系統在讀取時間與時間event(schedule/trigger)的限制,因此從java api取得的 nanosecond 的數值並不精確,越高的解析度(nanoseconds > microseconds > milliseconds)精確度越低,文中也提供了些使用上的建議。
  • 需要讀取精確的時間使用 System.currentTimeMillis()
  • 需要比較時間差異使用 System.nanoTime()
  • 需要等待系統回應(e.g. wait/sleep),設定時間別小於10 milliseconds


另外從二段 openjdk version "1.7.0-ea" 源始碼來看,wait 與 sleep 的 nanos 參數也僅是當作參考

Object.wait(long timeout, int nanos)
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
            timeout++;
        }

        wait(timeout);
    }
Thread.sleep(long millis, int nanos)
    public static void sleep(long millis, int nanos) throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

No comments: