Java 如何使用 TimeUnit 枚举将纳秒转换为秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/924208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert nanoseconds to seconds using the TimeUnit enum?
提问by phill
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?
这是什么意思?
采纳答案by Adam Rosenfield
Well, you could just divide by 1,000,000,000:
好吧,你可以除以 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.
如果您使用TimeUnit
转换,您将得到很长的结果,因此您将失去小数精度但保持整数精度。
回答by Nick Veys
TimeUnit is an enum, so you can't create a new one.
TimeUnit 是一个枚举,所以你不能创建一个新的。
The following will convert 1000000000000ns to seconds.
以下将 1000000000000ns 转换为秒。
TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
回答by pythonquick
回答by Zoltán
To reduce verbosity, you can use a static import:
为了减少冗长,您可以使用静态导入:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
- 从今以后只需输入
NANOSECONDS.toSeconds(elapsedTime);
回答by Lalit Narayan Mishra
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.
在变量中分配 endTime 可能会导致几纳秒。在这种方法中,您将获得确切的经过时间。
And then:
进而:
TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)
回答by Ayaz Alifov
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;
回答by Vova Perebykivskyi
JDK9+ solution using java.time.Duration
JDK9+使用java.time.Duration的解决方案
Duration.ofNanos(1_000_000L).toSeconds()
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofNanos-long-
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofNanos-long-
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#toSeconds--
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#toSeconds--