javatimeunit

How to convert nanoseconds to seconds using the TimeUnit enum?


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?


Solution

  • 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.