我正在分析一小段代码,这是一个更大的模拟的一部分,令我惊讶的是,STL函数等于(std :: equal)比一个简单的for循环慢得多,比较两个数组元素.我写了一个小测试用例,我认为这是两者之间的公平比较,而差异,使用Debian档案中的g ++ 6.1.1并不是无关紧要的.我正在比较有符号整数的两个四元素数组.我测试了std :: equal,operator ==和一个小的for循环.我没有使用std :: chrono来获得精确的时间,但是可以通过时间明确地看出差异./a.out.
我的问题是,给定下面的示例代码,为什么operator ==和重载函数std :: equal(调用operator ==我相信)需要大约40秒来完成,而手写循环只需要8s?我正在使用最新的基于英特尔的笔记本电脑.for循环在所有优化级别上都更快,-O1,-O2,-O3和-Ofast.我编译了代码
g++ -std=c++14 -Ofast -march=native -mtune=native
循环运行了很多次,只是为了使肉眼看清楚.模运算符表示对其中一个数组元素的廉价操作,并用于防止编译器优化循环.
#include<iostream>
#include<algorithm>
#include<array>
using namespace std;
using T = array<int32_t, 4>;
bool
are_equal_manual(const T& L, const T& R)
noexcept {
bool test{ true };
for(uint32_t i{0}; i < 4; ++i) { test = test && (L[i] == R[i]); }
return test;
}
bool
are_equal_alg(const T& L, const T& R)
noexcept {
bool test{ equal(cbegin(L),cend(L),cbegin(R)) };
return test;
} …Run Code Online (Sandbox Code Playgroud)