【发布时间】:2011-05-31 18:29:21
【问题描述】:
我正在制作一个将使用许多动态创建的对象(光线跟踪)的应用程序。与其只是一遍又一遍地使用 [new],我想我只是制作一个简单的内存系统来加快速度。在这一点上它非常简单,因为我不需要太多。
我的问题是:当我运行这个测试应用程序时,使用我的内存管理器会使用正确的内存量。但是当我使用 [new] 运行相同的循环时,它会使用 2.5 到 3 倍的内存。是我在这里没有看到的东西,还是 [new] 会产生巨大的开销?
我在 Win7 上使用 VS 2010。另外我只是使用任务管理器查看进程内存使用情况。
template<typename CLASS_TYPE>
class MemFact
{
public:
int m_obj_size; //size of the incoming object
int m_num_objs; //number of instances
char* m_mem; //memory block
MemFact(int num) : m_num_objs(num)
{
CLASS_TYPE t;
m_obj_size = sizeof(t);
m_mem = new char[m_obj_size * m_num_objs);
}
CLASS_TYPE* getInstance(int ID)
{
if( ID >= m_num_objs) return 0;
return (CLASS_TYPE*)(m_mem + (ID * m_obj_size));
}
void release() { delete m_mem; m_mem = 0; }
};
/*---------------------------------------------------*/
class test_class
{
float a,b,c,d,e,f,g,h,i,j; //10 floats
};
/*---------------------------------------------------*/
int main()
{
int num = 10 000 000; //10 M items
// at this point we are using 400K memory
MemFact<test_class> mem_fact(num);
// now we're using 382MB memory
for(int i = 0; i < num; i++)
test_class* new_test = mem_fact.getInstance(i);
mem_fact.release();
// back down to 400K
for(int i = 0; i < num; i++)
test_class* new_test = new test_class();
// now we are up to 972MB memory
}
【问题讨论】:
-
您的程序不完整。无论如何,我们可能都不想要这一切。
-
对不起。我试图编辑史诗格式失败,但有人在我之前编辑并锁定了我猜的我的更改。它不喜欢我放在那里的方式
-
它可能处于调试模式,有人正在跟踪 1000 万个分配?
-
它处于调试模式。我不知道这增加了那么多开销。在发布模式下构建它会降低到 600 MB
标签: c++ memory new-operator