我std::none_of使用i)for循环,ii)基于范围的for循环和iii)迭代器对三种不同的手动实现的性能进行了基准测试.令我惊讶的是,我发现虽然所有三个手动实现大致相同的时间,但std::none_of速度要快得多.我的问题是 - 为什么会这样?
我使用了谷歌基准测试库并编译了-std=c++14 -O3.运行测试时,我将进程的关联性限制为单个处理器.我使用GCC 6.2得到以下结果:
Benchmark Time CPU Iterations
--------------------------------------------------------
benchmarkSTL 28813 ns 28780 ns 24283
benchmarkManual 46203 ns 46191 ns 15063
benchmarkRange 48368 ns 48243 ns 16245
benchmarkIterator 44732 ns 44710 ns 15698
Run Code Online (Sandbox Code Playgroud)
在Clang 3.9上,虽然速度差较小,但std::none_of也比手动for循环快.这是测试代码(仅包括用于简洁的循环手册):
#include <algorithm>
#include <array>
#include <benchmark/benchmark.h>
#include <functional>
#include <random>
const size_t N = 100000;
const unsigned value = 31415926;
template<size_t N>
std::array<unsigned, N> generateData() {
std::mt19937 randomEngine(0);
std::array<unsigned, …Run Code Online (Sandbox Code Playgroud) 考虑以下在Clang 3.8上成功编译的问题-std=c++14.
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto indices = hana::range<unsigned, 0, 3>();
hana::for_each(indices, [&](auto i) {
hana::for_each(indices, [&](auto j) {
constexpr bool test = (i == (j == i ? j : i));
static_assert(test, "error");
});
});
}
Run Code Online (Sandbox Code Playgroud)
测试是非常不敏感的,但这不是重点.现在考虑一个替代版本,其中测试直接放在static_assert:
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto indices = hana::range<unsigned, 0, 3>();
hana::for_each(indices, [&](auto i) {
hana::for_each(indices, [&](auto j) {
static_assert((i == (j == i ? j …Run Code Online (Sandbox Code Playgroud)