如何使用TimeUnit枚举将纳秒转换为秒?

时间:2009-05-29 02:56:37

标签: java timeunit

如何将值从纳秒转换为秒?

以下是代码段:

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"); 
}}

错误是

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

这是什么意思?

8 个答案:

答案 0 :(得分:343)

TimeUnit Enum

以下表达式使用TimeUnit枚举(Java 5及更高版本)将纳秒转换为秒:

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

答案 1 :(得分:191)

嗯,你可以除以1,000,000,000:

long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1_000_000_000.0;

如果你使用TimeUnit进行转换,你会得到一个很长的结果,所以你将失去小数精度,但保持整数精度。

答案 2 :(得分:55)

TimeUnit是一个枚举,因此您无法创建新的。

以下内容将1000000000000ns转换为秒。

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

答案 3 :(得分:21)

要减少详细程度,可以使用静态导入:

import static java.util.concurrent.TimeUnit.NANOSECONDS;

- 此后只需输入

NANOSECONDS.toSeconds(elapsedTime);

答案 4 :(得分:6)

你应该写:

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

在变量中分配endTime可能会导致几纳秒。在这种方法中,您将获得确切的经过时间。

然后:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

答案 5 :(得分:4)

这将以double格式将时间转换为秒,这比整数值更精确:

double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;

答案 6 :(得分:1)

答案 7 :(得分:0)

this.player_spaceship = this.physics.add.sprite(400, 250, "player_spaceship"); this.player_spaceship.setCollideWorldBounds(true); // You *could* use the body here instead if you wanted! But since you have the convenience method, might as well use it. Java 8中,我像使用Kotlin

Duration.ofNanos(1_000_000_000)

了解更多https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html