c++ - c++ 编译器是否将多种算法合并为一个循环?

标签 c++ c++11 compiler-optimization

假设我们有以下代码:

int main () {
 int myints[] = {3,7,2,5,6,4,9};

 // using default comparison:
 std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
 std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';
}

编译器会把上面优化成一个循环吗?还是写在一个 for 循环中更好?

最佳答案

这取决于编译器。例如,我的编译器(x86_64 上的g++ 4.7.3)没有,保持两个独立的循环(使用-O3 编译时):

_main:
;=== initialization code omitted ===
        jmp     L2
L3:
        movl    (%rax), %edx
        cmpl    %edx, %ebx
        cmovg   %edx, %ebx
L2:
        addq    $4, %rax
        cmpq    %rbp, %rax
        jne     L3
;=== output code omitted ===
        jmp     L8
L6:
        movl    (%rax), %ecx
        cmpl    %ecx, (%rdx)
        cmovl   %rax, %rdx
L8:
        addq    $4, %rax
        cmpq    %rbp, %rax
        jne     L6
;=== output code omitted ===

关于c++ - c++ 编译器是否将多种算法合并为一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862003/

相关文章:

c++ - 多个ptime的平均值

c++ - 结构字段访问

c++ - std::istream 类型是 EqualityComparable 吗?

c++11 - std::future 和 clang 与 -stdlib=libstdc++

python - 为什么字符串乘法的字节码不同?

c++ - 按时使用重载运算符

c++ - get_input_port 方法位于 drake 的什么位置?

c++ - 铛+ libc++ : combination of make_tuple with make_shared leads to early object destruction

c++ - 不同版本的编译器(例如 GCC)会产生不同的性能吗?

functional-programming - 函数式编程的开销