Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of nanoseconds to milliseconds and nanoseconds < 999999 in Java

I'm wondering what the most accurate way of converting a big nanoseconds value is to milliseconds and nanoseconds, with an upper limit on the nanoseconds of 999999. The goal is to combine the nanoseconds and milliseconds values to ensure the maximum resolution possible with the limit given. This is for comparability with the sleep / wait methods and some other external library that gives out large nanosecond values.

Edit: my code looks like the following now:

while (hasNS3Events()) {                                     long delayNS = getNS3EventTSDelay();     long delayMS = 0;     if (delayNS <= 0) runOneNS3Event();     else {         try {             if (delayNS > 999999) {                 delayMS = delayNS / 1000000;                 delayNS = delayNS % 1000000;             }              EVTLOCK.wait(delayMS, (int)delayNS);         } catch (InterruptedException e) {          }     } } 

Cheers, Chris

like image 403
Chris Dennett Avatar asked Nov 29 '10 03:11

Chris Dennett


People also ask

How do you convert nanoseconds to seconds in Java?

We can just divide the nanoTime by 1_000_000_000 , or use the TimeUnit. SECONDS.

Is nanoseconds and milliseconds the same?

Nanosecond is one billionth of a second. Microsecond is one millionth of a second. Millisecond is one thousandth of a second.

How do you convert milliseconds to hours in Java?

If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations: int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); //etc...


2 Answers

Why not use the built in Java methods. The TimeUnit is part of the concurrent package so built exactly for you needs

  long durationInMs = TimeUnit.MILLISECONDS.convert(delayNS, TimeUnit.NANOSECONDS); 
like image 136
Shawn Vader Avatar answered Sep 22 '22 17:09

Shawn Vader


For an ever shorter conversion using java.util.concurrent.TimeUnit, equivalent to what Shawn wrote above, you can use:

    long durationInMs = TimeUnit.NANOSECONDS.toMillis(delayNS); 
like image 39
Ibrahim Arief Avatar answered Sep 20 '22 17:09

Ibrahim Arief