Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nanoseconds to seconds using the TimeUnit enum?

Tags:

java

timeunit

People also ask

How to convert nano time to seconds?

We can just divide the nanoTime by 1_000_000_000 , or use the TimeUnit. SECONDS.

How to convert nano time to seconds in Java?

So, in order to convert nanoseconds to second, divide it by 1000000000 as shown in the below example. double seconds = (double)duration/1000000000; System.

How do you convert milliseconds to seconds in Java?

Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).

Is nanoseconds and milliseconds the same?

Nanosecond is one billionth of a second. Microsecond is one millionth of a second. Millisecond is one thousandth of a second.


TimeUnit Enum

The following expression uses the TimeUnit enum (Java 5 and later) to convert from nanoseconds to seconds:

TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)

Well, you could just divide by 1,000,000,000:

long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1_000_000_000.0;

If you use TimeUnit to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.


TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

To reduce verbosity, you can use a static import:

import static java.util.concurrent.TimeUnit.NANOSECONDS;

-and henceforth just type

NANOSECONDS.toSeconds(elapsedTime);

You should write :

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.

And then:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

This will convert a time to seconds in a double format, which is more precise than an integer value:

double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;