Measure Time in Nano-Seconds


Since computers are getting faster and faster it might be insufficient to measure the time a certain task takes using only milli-seconds.
Since Java 5, the System class has a new method, nanoTime, that returns a nanosecond-resolution counter. You can’t use it for measuring absolute time, but it works great for measuring time differences.

The example below shows how to use it:


package com.javadb.examples;

public class Main {

    public static void main(String[] args) {

        long start = System.nanoTime();

        for (int i = 0; i < 10; i++) {
            System.out.println(i);
        }

        long end = System.nanoTime();

        System.out.println("Time: " + (end - start));


    }
}


Unfortunately, we have no guarantee that we will actually get nano-second measurements when we run this code.
But with a faster machine and a good JRE implementation, it’s a useful measurement for testing purposes.
You can find more information on this method in the JDK 5 documentation. Because of operating system characteristics, machine processing speed, and system load, you may get a wide variation in the values returned by the nanoTime method.

This is what the output was when run on the Javadb.com machine :)


0
1
2
3
4
5
6
7
8
9
Time: 824547

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: