问题
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:
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.
回答2:
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)
回答3:
TimeUnit is an enum, so you can't create a new one.
The following will convert 1000000000000ns to seconds.
TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
回答4:
To reduce verbosity, you can use a static import:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
NANOSECONDS.toSeconds(elapsedTime);
回答5:
You should write :
long startTime = System.nanoTime();
long estimatedTime = System.nanoTime() - startTime;
Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.
And then:
TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)
回答6:
This will convert a time to seconds in a double format, which is more precise than an integer value:
double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;
来源:https://stackoverflow.com/questions/924208/how-to-convert-nanoseconds-to-seconds-using-the-timeunit-enum