小编fro*_*777的帖子

为什么编译器不会在集合的元素上优化空的ranged-for循环?

在测试我的代码时,我注意到当for loop删除空的范围时,执行时间显着增加.通常我会认为编译器会注意到for循环没有用处,因此会被忽略.作为编译器标志我正在使用-O3(gcc 5.4).我还使用向量而不是集合来测试它,这似乎可以工作并在两种情况下都给出相同的执行时间.似乎迭代器的增量花费了所有额外的时间.

第一种情况下,ranged for循环仍然存在(慢):

#include <iostream>
#include <set>
int main () {
    long result;
    std::set<double> results;
    for (int i = 2; i <= 10000; ++i) {
        results.insert(i);
        for (auto element : results) {
            // no operation
        }
    }
    std::cout << "Result: " << result << "\n";
}
Run Code Online (Sandbox Code Playgroud)

第二种情况,删除了范围for循环(快速):

#include <iostream>
#include <set>
int main () {
    long result;
    std::set<double> results;
    for (int i = 2; i <= 10000; ++i) {
        results.insert(i);
    }
    std::cout …
Run Code Online (Sandbox Code Playgroud)

c++ compiler-optimization

28
推荐指数
4
解决办法
3458
查看次数

标签 统计

c++ ×1

compiler-optimization ×1