我一直试图通过循环展开来优化一些极其性能关键的代码(一种快速排序算法,在蒙特卡罗模拟中被称为数百万次).这是我试图加速的内循环:
// Search for elements to swap.
while(myArray[++index1] < pivot) {}
while(pivot < myArray[--index2]) {}
Run Code Online (Sandbox Code Playgroud)
我尝试展开类似的东西:
while(true) {
if(myArray[++index1] < pivot) break;
if(myArray[++index1] < pivot) break;
// More unrolling
}
while(true) {
if(pivot < myArray[--index2]) break;
if(pivot < myArray[--index2]) break;
// More unrolling
}
Run Code Online (Sandbox Code Playgroud)
这完全没有区别所以我把它改成了更易读的形式.我曾经尝试过循环展开,但我有类似的经历.鉴于现代硬件上的分支预测器的质量,何时(如果有的话)循环展开仍然是一个有用的优化?
language-agnostic optimization performance micro-optimization
向量化代码是一个好主意吗?在什么时候这样做有什么好的做法?下面会发生什么?