【问题标题】:My StopWatch has wrong nano and millis, but right seconds我的秒表有错误的 nano 和 millis,但正确的秒
【发布时间】:2022-01-17 16:58:23
【问题描述】:

我为自己的小库实现了一个秒表类,并通过执行以下 sn-p 对其进行了测试:

public class Main {
    public static void main(String[] args) throws Exception {
        StopWatch sw = new StopWatch();
        sw.start();
        Thread.sleep(3000);
        sw.stop();
        System.out.println(sw.getMilli());
        System.out.println(sw.getDuration().getNano());
        System.out.println(sw.getDuration().getSeconds());
    }
}

我得到以下结果:

20
2011600
3

您可以看到数字不同。我检查了我的秒表课程大约 10 次,但我找不到错误。你能找到他们吗?

这是我的秒表实现:

import java.time.Instant;
import java.time.Duration;

public class StopWatch {
    private Instant startDate;
    private Instant stopDate;
    
    public StopWatch() {
        reset();
    }
    
    public void start() {
        if (startDate == null) {
            startDate = Instant.now();
        }
    }
    
    public void stop() {
        if (stopDate == null && startDate != null) {
            stopDate = Instant.now();
        }
    }
    
    public void reset() {
        startDate = null;
        stopDate = null;
    }
    
    public Duration getDuration() {
        if (startDate != null && stopDate != null) {
            return Duration.between(startDate, stopDate);
        }
        
        return null;
    }
    
    public long getMilli() {
        if (startDate != null && stopDate != null) {
            return Duration.between(startDate, stopDate).getNano() / 1000000L;
        }
        
        return 0;
    }
}

【问题讨论】:

  • 一毫秒内没有 100,000 纳秒。
  • 也可能是整数除法的问题,因为您没有将分母指定为长。例如在 getMilli 中使用 / 1000L
  • 已修复,但这似乎不是实际问题。秒和其他单位还是有区别的。
  • 一毫秒也没有 1000 纳秒。
  • 我假设您已经阅读了 getNano()getSeconds() 的 javadoc 并了解 getNano() 的作用?

标签: java time


【解决方案1】:

我误解了 Duration 类的对象是如何工作的。 getNano() 不会返回范围之间的总纳秒数,而是返回不适合整秒的其余纳秒。我删除了 getDuration() 并像这样重新实现了 getMilli():

public long getMilli() {
    if (startDate != null && stopDate != null) {
        Duration duration = Duration.between(startDate, stopDate);
        long nanos = duration.getSeconds() * 1000000000 + duration.getNano(); 
        return nanos / 1000000;
    }
    
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多