修复 StopWatch.stop时间回拨时计算结果为负的问题(pr#1417@Gitee)

This commit is contained in:
Looly
2025-12-25 23:42:41 +08:00
parent 1da3acca67
commit c20850dce3
2 changed files with 28 additions and 3 deletions

View File

@@ -30,8 +30,7 @@ import java.util.concurrent.TimeUnit;
* 比如我们可以记录多段代码耗时时间然后一次性打印StopWatch提供了一个prettyString()函数用于按照指定格式打印出耗时)
*
* <p>
* 此工具来自https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/StopWatch.java
*
* 此工具来自:<a href="https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/StopWatch.java">StopWatch</a>
* <p>
* 使用方法如下:
*
@@ -195,7 +194,7 @@ public class StopWatch {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
final long lastTime = System.nanoTime() - this.startTimeNanos;
final long lastTime = Math.max(System.nanoTime() - this.startTimeNanos, 0);
this.totalTimeNanos += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (null != this.taskList) {

View File

@@ -0,0 +1,26 @@
package cn.hutool.v7.core.date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
public class IssueIDFMXJTest {
@Test
void stopWatchNegativeTimeTest() throws NoSuchFieldException, IllegalAccessException {
final StopWatch stopWatch = new StopWatch();
stopWatch.start("负耗时测试任务");
// 反射修改startTimeNanos为当前时间+1秒模拟nanoTime回退
final Field startTimeNanosField = StopWatch.class.getDeclaredField("startTimeNanos");
startTimeNanosField.setAccessible(true);
startTimeNanosField.set(stopWatch, System.nanoTime() + 1_000_000_000);
stopWatch.stop();
Assertions.assertEquals(0, stopWatch.getLastTaskTimeNanos());
Assertions.assertEquals(0, stopWatch.getTotalTimeNanos());
}
}