【发布时间】:2014-04-20 22:35:14
【问题描述】:
我将 Java GC 测试程序移植到 C++(参见下面的代码)和 Python。 Java 和 Python 的性能远高于 C++,我认为这是由于每次都必须调用 new 来创建字符串。我试过使用 Boost 的fast_pool_allocator,但这实际上使性能从 700ms 恶化到 1200ms。我是否使用了错误的分配器,或者我应该做些什么?
编辑:使用g++ -O3 -march=native --std=c++11 garbage.cpp -lboost_system 编译。 g++ 是版本 4.8.1
Python 的一次迭代大约需要 300 毫秒,而 Java 大约需要 50 毫秒。 std::allocator 大约需要 700 毫秒,boost::fast_pool_allocator 大约需要 1200 毫秒。
#include <string>
#include <vector>
#include <chrono>
#include <list>
#include <iostream>
#include <boost/pool/pool_alloc.hpp>
#include <memory>
//#include <gc/gc_allocator.h>
using namespace std;
#include <sstream>
typedef boost::fast_pool_allocator<char> c_allocator;
//typedef std::allocator<char> c_allocator;
typedef basic_string<char, char_traits<char>, c_allocator> pool_string;
namespace patch {
template <typename T> pool_string to_string(const T& in) {
std::basic_stringstream<char, char_traits<char>, c_allocator> stm;
stm << in;
return stm.str();
}
}
#include "mytime.hpp"
class Garbage {
public:
vector<pool_string> outer;
vector<pool_string> old;
const int nThreads = 1;
//static auto time = chrono::high_resolution_clock();
void go() {
// outer.resize(1000000);
//old.reserve(1000000);
auto tt = mytime::msecs();
for (int i = 0; i < 10; ++i) {
if (i % 100 == 0) {
cout << "DOING AN OLD" << endl;
doOld();
tt = mytime::msecs();
}
for (int j = 0; j < 1000000/nThreads; ++j)
outer.push_back(patch::to_string(j));
outer.clear();
auto t = mytime::msecs();
cout << (t - tt) << endl;
tt = t;
}
}
void doOld() {
old.clear();
for (int i = 0; i < 1000000/nThreads; ++i)
old.push_back(patch::to_string(i));
}
};
int main() {
Garbage().go();
}
【问题讨论】:
-
fast_pool_allocator docs 似乎表明你确实用错了:
pool_allocator用于连续块(例如new char[n]),fast_pool_allocators用于单个事物(例如new char)。 -
谢谢。我刚试过这个,但我厌倦了等待它打印一个数字(即它花了很长时间)
-
@user315118 - 您的帖子中没有提及使用的编译器、构建应用程序时在优化方面使用的编译器选项等。如果您要发布声称在某些方面执行的代码时间单位,您还必须发布您使用的编译器和选项。否则,我们可以正确地假设您使用的是旧的编译器、损坏的编译器,或者在没有完全启用优化的情况下进行编译。
-
你是说每个循环需要0.7-1.2s?在我的机器上,使用标准分配器大约需要 0.19 秒。要么你在一些相当慢的硬件上运行,要么你没有启用优化。
-
@PaulMcKenzie 谢谢。我已经用这些信息更新了问题。
标签: c++ linux memory-management boost memory-pool