How to convert nanoseconds to seconds using the TimeUnit enum?

phill picture phill · May 29, 2009 · Viewed 250.1k times · Source

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?

Answer

pythonquick picture pythonquick · May 29, 2009

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)