在 Java 中将纳秒转换为毫秒和纳秒 < 999999

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4300653/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:35:09  来源:igfitidea点击:

Conversion of nanoseconds to milliseconds and nanoseconds < 999999 in Java

javatimemillisecondsnanotime

提问by Chris Dennett

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.

我想知道将大纳秒值转换为毫秒和纳秒的最准确方法是什么,纳秒上限为 999999。目标是将纳秒和毫秒值结合起来,以确保最大分辨率可能与限制给。这是为了与睡眠/等待方法和其他一些给出大纳秒值的外部库进行比较。

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

干杯,克里斯

采纳答案by Ignacio Vazquez-Abrams

Just take the divmod of it with 1000000.

只需用 1000000 取它的 divmod 即可。

回答by Shawn Vader

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

为什么不使用内置的 Java 方法。TimeUnit 是并发包的一部分,因此完全满足您的需要

  long durationInMs = TimeUnit.MILLISECONDS.convert(delayNS, TimeUnit.NANOSECONDS);

回答by Ibrahim Arief

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

对于使用 更短的转换java.util.concurrent.TimeUnit,相当于 Shawn 上面写的内容,您可以使用:

    long durationInMs = TimeUnit.NANOSECONDS.toMillis(delayNS);