How to convert nanoseconds to seconds using the TimeUnit enum?

前端 未结 8 2067
小鲜肉
小鲜肉 2020-12-07 09:37

How to convert a value from nanoseconds to seconds?

Here\'s the code segment:

import java.io.*;
import java.util.concurrent.*; 
..

class Stamper          


        
相关标签:
8条回答
  • 2020-12-07 09:55

    JDK9+ solution using 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#toSeconds--

    0 讨论(0)
  • 2020-12-07 09:56

    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;
    
    0 讨论(0)
  • 2020-12-07 10:03

    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)
    
    0 讨论(0)
  • 2020-12-07 10:11

    In Java 8 or Kotlin, I use Duration.ofNanos(1_000_000_000) like

    val duration = Duration.ofNanos(1_000_000_000)
    logger.info(String.format("%d %02dm %02ds %03d",
                    elapse, duration.toMinutes(), duration.toSeconds(), duration.toMillis()))
    

    Read more https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

    0 讨论(0)
  • 2020-12-07 10:15

    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)
    
    0 讨论(0)
  • 2020-12-07 10:18

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

    The following will convert 1000000000000ns to seconds.

    TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
    
    0 讨论(0)
提交回复
热议问题