【发布时间】: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()的作用?