Search code examples
javaframe-rate

What does the printed out result mean. System.nanoTime() in Java


I don't understand what i get from printing out timeStarted, then printing out getTime(). What is it that i am printing out? What does the printed out values mean?

I have just began learning java and are trying to understand how to work with frame rates.

Time.java

public class Time {
    public static double timeStarted = System.nanoTime();
    public static double getTime() { return (System.nanoTime() - timeStarted) * 10E-9; }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Time time = new Time();
        System.out.println(time.timeStarted);
        System.out.println(time.getTime());
    }
}

Console:

4.24512563119081E14
0.01404352

Solution

  • System.nanoTime() returns the current value of the most precise available system timer in nanoseconds. The value returned represents nanoseconds passed since some fixed but arbitrary time.

    System.nanoTime() has nothing to do with dates and time-of-day. System.nanoTime() is an ongoing count of passing nanoseconds, nothing more.

    Multiplying the return value of System.nanoTime() with 10E-9 will yield the current count in seconds, times 10. (To properly convert to seconds, you would have to multiply by 1e-9. I am guessing this was the original intention?)

    Since you are substracting the current count from the starting count, the return value of getTime() will represent the amount of time that has passed since the Time-class was loaded, in seconds, times 10.