nanoTime? What is it?

It is a Java function used to calculate Elapsed Time.

The main reason why you want to know the elapsed time of the method executions is to identify bottlenecks and long running methods, or simply if you want to let your management see how awesomely fast your methods are.

If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime().

You cannot use System.currentTimeMillis(), unless you don’t mind your result being wrong.

Calculating Elapsed Time

The main reason why you want to know the elapsed time of the method executions is to identify bottlenecks and long running methods, or simply if you want to let your management see how awesomely fast your methods are.

Difference between nanoTime and CurrentTimeMillis

The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. As these are designed for specific reasons, it is important to choose the right one for your needs. The reason is that no computer’s clock is perfect. It is sometimes off and periodically needs to be corrected. This correction might either happen manually, or in the case of most machines, there’s a process that runs and continually issues small corrections to the system clock or wall-clock. These shifts tend to happen often. Another such correction happens whenever there is a leap second.

Since nanoTime’s purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use for calculating elapsed time.

You may think, “So what? This will not matter that much”, to which I say, maybe not, but overall, isn’t correct code just better than incorrect code? Besides, nanoTime is shorter to type anyway.

This has been a very interesting subject and I am learning a lot about this, it is mind boggling.

 

Leave a Reply

Your email address will not be published. Required fields are marked *