谁更快:BOOST_FOREACH宏或为

Who is faster: BOOST_FOREACH macros or for

本文关键字:FOREACH BOOST      更新时间:2023-10-16

我测试了我的程序,曾经决定使用 const_iteratorBOOST_FOREACH宏更改为简单的for循环。

我收到了意想不到的结果:程序使用for工作速度变慢。

然后我写了小测试应用程序:

std::vector<int> vec;
for (int i = 0; i != 50000000; ++i)
    vec.push_back(i);

time_t t1 = clock();
int sum1 = 0;
for (std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it)
    sum1 += *it;
std::cout << ulong(clock() - t1);
time_t t2 = clock();
int sum2 = 0;
BOOST_FOREACH(auto &it, vec) {
    sum2 += it;
}
std::cout << ulong(clock() - t2);

这是输出:

34963
26964

为什么会这样?

  1. 代码中有未定义的行为。0+...+50,000,000 的总和远远超出了MAX_INT。 整数溢出 == 未定义的行为 , 未定义的行为== 您的测试无效。

  2. 假设您在构建项目时进行了全面优化,我猜结果是由于 CPU 预热以及由于在第二个基准测试中已经缓存了一些数据的事实而发生的。尝试切换基准测试,看看会发生什么