Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)

How to convert a value from nanoseconds to seconds?

Here's the code segment:


import java.util.concurrent.*; 


class Stamper { 

public static void main (String[] args) { 

long start = System.nanoTime(); 

//some try with nested loops 

long end = System.nanoTime(); 

long elapsedTime = end - start;

System.out.println("elapsed: " + elapsedTime + "nano seconds\n");

//convert to seconds 

TimeUnit seconds = new TimeUnit(); 

System.out.println("which is " + seconds.toSeconds(elapsedTime) + " seconds"); 


The error is  enum types may not be instantiated.

What does this mean?

1 Answer

0 votes
by (46k points)

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.

Browse Categories