Java System.nanoTime and System.currentTimeMillis

In this tutorial, we will learn two most commonly used Java System functions : System.nanoTime and
System.currentTimeMillis(). Both are time related functions, i.e. to get a time from the system (not the current
time ). Let’s take a look :

System.nanoTime() :

‘System.nanoTime()’ returns a long value : current value of the running JVM in nanoseconds. It returns a time since
some fixed but arbitary origin time.

The values of a ‘nanoTime’ method can be used to find out the difference at two points i.e. we will take one reading
before a method starts and another reading after the method is completed . Now, the difference between these two reading
is the time taken to execute the method in ‘NanoSeconds’ .

Above method is not actually a recommended way to take profiling for a program because the time takes to execute a
piece of code may differ on different hardware and operating system.

Let’s take a look how ‘System.nanoTime’ works with an example :


/*
 * Copyright (C) 2017 codevscolor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * Example Class
 */
public class ExampleClass {

    /**
     * System.out.println utility method
     *
     * @param value : value to print
     */
    static void print(String value) {
        System.out.println(value);
    }

    /**
     * main method for this class
     */
    public static void main(String[] args) {

        //take the start time in nano second
        long startTime = System.nanoTime();

        print("Start time in nano : " + startTime);

        try {
            Thread.sleep(100l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //get the ending time in nano second
        long endTime = System.nanoTime();
        print("Ending time in nano : " + endTime);

        print("Difference between start and end time in nano second is " + (endTime - startTime));


    }
}

On my system , it prints the following output : ( on your system, output will be different )

Start time in nano : 21257944588773
Ending time in nano : 21258047616446
Difference between start and end time in nano second is 103027673

Also, it maynot be same on each iteration. In this program, we have add one delay to the method using ‘Thread.sleep()
‘ method.

System.currentTimeMillis() :

This method returns the current time in milliseconds. The granularity of the value depends on Operating system. It
actually returns the current time in milliseconds since January 1, 1970 UTC. We can use ‘currentTimeMillis’ to profile a
method same as like ‘nanoTime’ :


/*
 * Copyright (C) 2017 codevscolor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * Example Class
 */
public class ExampleClass {

    /**
     * System.out.println utility method
     *
     * @param value : value to print
     */
    static void print(String value) {
        System.out.println(value);
    }

    /**
     * main method for this class
     */
    public static void main(String[] args) {

        //take the start time in milli second
        long startTime = System.currentTimeMillis();

        print("Start time in milli : " + startTime);

        try {
            Thread.sleep(100l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //get the ending time in milli second
        long endTime = System.currentTimeMillis();
        print("Ending time in milli : " + endTime);

        print("Difference between start and end time in milli second is " + (endTime - startTime));


    }
}

Sample Output :

Start time in milli : 1505755601923
Ending time in milli : 1505755602028
Difference between start and end time in milli second is 105

We have paused the method for 100 milliseconds using ‘Thread.sleep()’ method, but you can see that the difference
between start and end time is 105 milliseconds. It will different on different system. Try running the program multiple
times and you can see different values.

You can get more accurate results from ‘nanoTime()’ as compared to ‘currentTimeMillis()’ but ‘nanoTime()’ is more
expensive call than ‘currentTimeMillis()’

Leave a Reply