Back

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

How to convert a value from nanoseconds to seconds?

Here's the code segment:

import java.io.*;

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

Stamper.java:16:  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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers

500 comments

108k users

Browse Categories

...