tags:

views:

2593

answers:

3

how do i convert this value from nano seconds to seconds?

I have the following 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 I get is

stamper.java:16:  enum types may not be instantiated.

I'm not sure what this means?

+2  A: 

TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.


TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
Nick Veys
+3  A: 

Well, you could just divide by 1,000,000,000:

long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1000000000.0;

If you use TimeUnit to convert, you'll only get an integer result, so you'll lose a significant amount of precision.

Adam Rosenfield
In most cases, I think this is probably the best solution. It's certainly a lot quicker to read.
Daniel Straight
I would change make 1000000000 a double to force double precision division.
Steve Kuo
1000000000.0 is already a double; a float constant would be 1000000000.0f.
Adam Rosenfield
But what if the number of nanoseconds in a second changes? :P
geofftnz
A: 

Use the following expression to get the seconds:

TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)
pythonquick