我目前正在尝试了解时间复杂度,因此,我编写了一个向下嵌入的测试用例。问题是虽然输入的最后一个索引中的输入大小变得相当大,但测量的时间有时会比前一个更短。
public class Main{
public static void test(int n) {
int num = 0;
for (int i = 0; i <= n; i++) {
num = num + i;
}
}
public static void main(String[] args) {
int[] inputAxis = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, 250000};
for (int i = 0; i < 10; i++) {
long total = 0;
long clockIn = System.nanoTime();
for (int j = 0; j < 1000; j++) { //PROBLEM HERE
test(inputAxis[i]);
}
long clockOut = System.nanoTime();
total = clockOut - clockIn;
System.out.println(total);
}
}
}
我观察到的:
1- 没有标记为循环,一切正常。
2- 当我修改 for 循环时,例如 for (int j = 0; j < 100000; j++), everything also works fine.
但是我需要这个 for 循环来精确迭代 1000 次,所以第二次观察对我来说不是一个选择。