最开始我使用了这种测试方式, 测试了 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);
- }
- }
image.png
测试结果, 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);
- }
- }
image.png
果然慢了下来
但是测试了几次之后发现时间极其不稳定
- 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);
- }
ceshi
测试了几次, 大概就保持在 330ms 左右
330000/1000000
大概是 330nm 一个循环周期
系统时间改为 nm 之后的时间
有想了想 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);
- }
- }
image.png
本次测试就是玩一玩, 无实际意义, 很多因素都没有考虑
来源: http://www.jianshu.com/p/9f4b922dd310