我在这里遇到了一个非常不寻常的问题。似乎调用 Thread.sleep(n),其中 n > 0 会导致以下 System.nanoTime() 调用难以预测。
下面的代码演示了这个问题。
在我的电脑(rMBP 15" 2015,OS X 10.11,jre 1.8.0_40-b26)上运行它会输出以下结果:
Control: 48497
Random: 36719
Thread.sleep(0): 48044
Thread.sleep(1): 832271
在运行 Windows 8 的虚拟机上(VMware Horizon、Windows 8.1 为 1.8.0_60-b27):
Control: 98974
Random: 61019
Thread.sleep(0): 115623
Thread.sleep(1): 282451
但是,在企业服务器(VMware、RHEL 6.7、jre 1.6.0_45-b06)上运行它:
Control: 1385670
Random: 1202695
Thread.sleep(0): 1393994
Thread.sleep(1): 1413220
这出乎我意料的结果。
显然 Thread.sleep(1) 会影响以下代码的计算。我不知道为什么会这样。有人有线索吗?
谢谢!
public class Main {
public static void main(String[] args) {
int N = 1000;
long timeElapsed = 0;
long startTime, endTime = 0;
for (int i = 0; i < N; i++) {
startTime = System.nanoTime();
//search runs here
endTime = System.nanoTime();
timeElapsed += endTime - startTime;
}
System.out.println("Control: " + timeElapsed);
timeElapsed = 0;
for (int i = 0; i < N; i++) {
startTime = System.nanoTime();
//search runs here
endTime = System.nanoTime();
timeElapsed += endTime - startTime;
for (int j = 0; j < N; j++) {
int k = (int) Math.pow(i, j);
}
}
System.out.println("Random: " + timeElapsed);
timeElapsed = 0;
for (int i = 0; i < N; i++) {
startTime = System.nanoTime();
//search runs here
endTime = System.nanoTime();
timeElapsed += endTime - startTime;
try {
Thread.sleep(0);
} catch (InterruptedException e) {
break;
}
}
System.out.println("Thread.sleep(0): " + timeElapsed);
timeElapsed = 0;
for (int i = 0; i < N; i++) {
startTime = System.nanoTime();
//search runs here
endTime = System.nanoTime();
timeElapsed += endTime - startTime;
try {
Thread.sleep(2);
} catch (InterruptedException e) {
break;
}
}
System.out.println("Thread.sleep(1): " + timeElapsed);
}
}
基本上我在一个while循环中运行一个搜索,每次迭代都会通过调用Thread.sleep()来中断。我想从运行搜索的总时间中排除睡眠时间,所以我使用 System.nanoTime() 来记录开始和结束时间。但是,正如您在上面注意到的那样,这效果不佳。
有没有办法解决这个问题?
感谢您的任何意见!