【发布时间】:2019-03-06 07:17:57
【问题描述】:
我尝试使用boost::pool 来减少内存分配的 CPU 消耗,但 profiling 测试代码结果不如预期。
这是测试代码。
main1.cpp
#include "pool_singleton.h"
int main()
{
const int size = 400000;
for (int i = 0; i < 100000; ++i)
{
auto obj = pNew uint8_t[size]; // use singleton_pool
pDelete(obj, size);
}
return 0;
}
main2.cpp
#include "pool_singleton.h"
int main()
{
const int size = 400000;
for (int i = 0; i < 100000; ++i)
{
auto obj = new uint8_t[size];
delete[] obj;
}
return 0;
}
pool_singleton.h
#pragma once
#include <iostream>
#include <memory>
// boost
#include <boost/pool/singleton_pool.hpp>
struct pNewTag{};
typedef boost::singleton_pool<pNewTag, 1> pool;
inline void* operator new (size_t size, int num)
{
auto ptr = pool::ordered_malloc(size);
return ptr;
}
template<int N>
struct memMan
{
static memMan<N> x;
inline static void delete_ptr(void *p, size_t size)
{
pool::free(p, size);
}
static inline void pool_destroy()
{
pool::purge_memory();
}
};
template<int N>
memMan<N> memMan<N>::x;
#define pNew new(1)
#define pDelete(p, size) memMan<0>::delete_ptr(p, size)
#define purge memMan<0>::pool_destroy()
main1.cpp 的 CPU 使用率是 main2.cpp 的两倍。
我预计 main1.cpp 的 CPU 使用率会随着时间的推移而下降,但直到最后它仍然很高。
问题是
- 我的 singleton_pool 使用有误吗?
- 有没有办法减少singleton_pool的cpu消耗?
- 还有其他减少内存分配的 CPU 消耗的想法吗?
【问题讨论】:
-
为什么是ordered_malloc?你为什么输出 i ?写入标准输出会影响您的基准。
-
I expected that the CPU usage of main2.cpp will drop as time passes, but it remained high until the end你的意思是 main1 吗? -
我使用
ordered_malloc来分配数组。有没有办法不使用ordered_malloc?输出 i 只是检查语句。我忘记抹掉了。main1.cpp的 CPU 负载高于main2.cpp的结果没有改变。 -
I expected that the CPU usage of main2.cpp will drop as time passes, but it remained high until the end do you mean main1 ?是的。感谢您指出这一点。 -
您为什么希望 CPU 使用率下降?为什么 CPU 不能尽可能快地完成工作?为什么 CPU 的运行速度会比它能够运行的速度慢,在这两种情况下,你已经给它做了大量的工作,而没有任何东西可以阻止它完成这些工作?
标签: c++ boost memory-management