最开始我使用了这种测试方式,测试了1百万次for循环
public class Main {
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++){
}
long stop = System.currentTimeMillis();
System.out.println(stop - start);
}
}
测试结果,what???4ms这处理器这么快吗,自己的老爷机心里还是有点B数的,一定的那个智能的编译器或者时jvm给我做了优化,于是
public class Main {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++){
Thread.sleep(0);
}
long stop = System.currentTimeMillis();
System.out.println(stop - start);
}
}
果然慢了下来
但是测试了几次之后发现时间极其不稳定
public class Main {
public static void main(String[] args) throws InterruptedException {
long start = 0;
long stop = 0;
long sum = 0;
for (int i = 0; i < 100; i++){
start = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++){
Thread.sleep(0);
}
stop = System.currentTimeMillis();
sum += (stop - start);
}
System.out.println(sum / 100);
}
测试了几次,大概就保持在330ms左右。
330000/1000000
大概是330nm一个循环周期
有想了想sleep会涉及一些线程调度的问题吗,那不是浪费了很多很多时间,这种测试方式没什么用啊
想了想
public class Main {
public static void main(String[] args) {
long start = 0;
long stop = 0;
long forStart = 0;
long forStop = 0;
long forSum = 0;
long sum = 0;
for (int i = 0; i < 100; i++){
start = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++){
forStart = System.nanoTime();
forStop = System.nanoTime();
forSum += (forStop - forStart);
}
stop = System.currentTimeMillis();
sum += (stop - start);
}
System.out.println(sum/100);
System.out.println(forSum/100000000);
System.out.println(sum / 100 - forSum /100000000);
}
}
【本次测试就是玩一玩,无实际意义,很多因素都没有考虑】
知乎里看到的一个关于时间测试的答案(所以说认真的了解jvm还是非常非常有用处的)
https://www.zhihu.com/question/58735131/answer/158460810