谁更快:BOOST_FOREACH宏或为
Who is faster: BOOST_FOREACH macros or for
我测试了我的程序,曾经决定使用 const_iterator
将BOOST_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
为什么会这样?
-
代码中有未定义的行为。0+...+50,000,000 的总和远远超出了MAX_INT。 整数溢出 == 未定义的行为 , 未定义的行为== 您的测试无效。
-
假设您在构建项目时进行了全面优化,我猜结果是由于 CPU 预热以及由于在第二个基准测试中已经缓存了一些数据的事实而发生的。尝试切换基准测试,看看会发生什么
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- 没有显式声明的int[]中的foreach
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- c++使用foreach使数组为null
- 使用 BOOST property_tree / iostreams / 文件系统 / foreach - 结果出现链接
- 在BOOST foreach中使用difference_type
- 自动定义来自CRTP的访问者(CRTP使用boost foreach和boost变体)
- std::foreach with boost::bind