灵感来自这个问题:
Why is it faster to process a sorted array than an unsorted array?
Why is it faster to process a sorted array than an unsorted array?
我写了自己的分支预测实验:
public class BranchPrediction { public static void main(final String[] args) { long start; long sum = 0; /* No branch */ start = System.nanoTime(); sum = 0; for (long i = 0; i < 10000000000L; ++i) sum += i; System.out.println(System.nanoTime() - start); System.out.println(sum); /* With branch */ start = System.nanoTime(); sum = 0; for (long i = 0; i < 10000000000L; ++i) if (i >= 0) sum += i; System.out.println(System.nanoTime() - start); System.out.println(sum); /* No branch (again) */ start = System.nanoTime(); sum = 0; for (long i = 0; i < 10000000000L; ++i) sum += i; System.out.println(System.nanoTime() - start); System.out.println(sum); /* With branch (again) */ start = System.nanoTime(); sum = 0; for (long i = 0; i < 10000000000L; ++i) if (i >= 0) sum += i; System.out.println(System.nanoTime() - start); System.out.println(sum); } }
结果让我感到困惑:根据程序输出,带分支的循环比没有分支循环的循环可靠得快.
输出示例:
7949691477 -5340232226128654848 6947699555 -5340232226128654848 7920972795 -5340232226128654848 7055459799 -5340232226128654848
为什么会这样?
编辑:
>反汇编类显示Java编译器没有优化(遗漏)任何东西(https://gist.github.com/HouzuoGuo/5692424)
> Why is it faster to process a sorted array than an unsorted array?作者使用的Java基准技术与我的相同.
>该机器是Intel核心i7,运行Linux 3.2 64位和Oracle JVM 1.7 64位
>当我超过循环迭代的次数时,with-branch循环比非分支循环运行多SECONDS.
解决方法
原文地址:https://www.jb51.cc/java/128423.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。