0 votes
1 view
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 (46.1k 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 !


Categories

...