#include <chrono>
#include <iostream>
using namespace std;
#define START_LOG_TIME() \
std::chrono::steady_clock::time_point t1 = \
std::chrono::steady_clock::now(); \
std::chrono::steady_clock::time_point t2 = t1; \
std::chrono::duration<double> time_used = \
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
#define PRINT_COST_TIME(name) \
t2 = std::chrono::steady_clock::now(); \
time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1); \
std::cout << name << " TIME COST: " << (time_used.count() * 1000) \
<< " ms." << std::endl; \
t1 = t2;
// #define MYMEMPOOL
class A {
public:
static void* operator new(size_t size);
static void operator delete(void* phead);
static int new_cnt_; // 每分配一次类A+1
static int mempool_cnt_; // 每分配一次内存池+1
private:
A* next;
static A* free_pos_; // 总是指向一块可以分配出去的内存的首地址
static int trunk_cnt_; // 一次分配类A的内存的倍数,作为内存池的大小
};
void* A::operator new(size_t size) {
#ifdef MYMEMPOOL
A* ptr = (A*)malloc(size);
return ptr;
#endif
A* tmp_link = nullptr;
if (free_pos_ == nullptr) {
size_t real_size = trunk_cnt_ * size;
free_pos_ = reinterpret_cast<A*>(new char[real_size]); // 这里使用传统new,调用传统底层malloc
tmp_link = free_pos_;
for (; tmp_link != &free_pos_[trunk_cnt_ - 1]; ++tmp_link) {
tmp_link->next = tmp_link + 1;
}
tmp_link->next = nullptr;
++mempool_cnt_;
cout << "mempool_cnt_:" << mempool_cnt_ << endl;
}
tmp_link = free_pos_;
free_pos_ = free_pos_->next;
++new_cnt_;
cout << "new_cnt_:" << new_cnt_ << endl;
return tmp_link;
}
void A::operator delete(void* phead) {
#ifdef MYMEMPOOL
free(phead);
#endif
(static_cast<A*>(phead))->next = free_pos_;
free_pos_ = static_cast<A*>(phead); // 不是真正的释放,而是还给内存池,以便下次申请使用
}
int A::new_cnt_ = 0;
int A::mempool_cnt_ = 0;
A* A::free_pos_ = nullptr;
int A::trunk_cnt_ = 5; // 一次分配5倍类A的内存,作为内存池的大小
int main() {
START_LOG_TIME();
for (int i = 0; i < 10; i++) {
A* pa = new A();
}
PRINT_COST_TIME("mempool test");
}