Reputation: 5
I tried to use boost::pool
to reduce CPU consumption of memory allocation, but profiling test codes result was not as expected.
This is the test code.
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's CPU usage was twice as high as main2.cpp.
I expected that the CPU usage of main1.cpp will drop as time passes, but it remained high until the end.
The questions are
Upvotes: 0
Views: 143
Reputation: 182779
You are thinking about CPU usage wrong. If the CPU usage is less than 100%, that means that resources on the CPU are being wasted. If the CPU usage is 100%, that means the CPU is making forward progress as quickly as it can.
All other things being equal, for a task that is basically just asking the CPU to do work, the higher the CPU usage the better as that means the work is getting done as quickly as possible. The CPU will run at full speed so long as there is work to be done unless it can't for some reason such as having to wait for I/O or overheating -- all bad things.
Instead, measure the total CPU consumption for the work. More efficient code will need less CPU to get equivalent work done.
I expected that the CPU usage of main1.cpp will drop as time passes, but it remained high until the end.
That is fantastic. That means the CPU was getting work done as quickly as it could until it got all the work done. Any drop below 100% while the CPU still has work to do just indicates some inefficiency preventing the CPU from getting work done as quickly as it is capable of.
Upvotes: 2