I got a problem when I tried to create and delete an instance of the class in a loop.
Execution time of iterations is quite different. As I understand it, this is associated with the removal of objects from memory. However, the behavior of this operation I do not understand. Why time is different? How do I fix it? Time is steady when I’m deleting the object in a separate thread.
class NODE{
public:
NODE(){}
NODE* add(NODE* node)
{
children.push_back(node);
return node;
}
virtual ~NODE()
{
for(vector<NODE*>::iterator it = children.begin(); it != children.end(); ++it)
{
delete *it;
}
}
vector<NODE*> children;
};
NODE* create()
{
NODE* node( new NODE() );
for (int i=0; i<200;i++) {
NODE* subnode = node->add( new NODE());
for (int k=0; k<20; k++) subnode->add( new NODE());
}
return node;
}
int main()
{
NODE* root;
unsigned t;
for (int i=0; i<30; i++){
t = clock();
cout << "Create... ";
root = create();
delete root;
cout<< clock()-t << endl;
}
}
ADDED:
I’m confused. When I run program out of VS it works fine…
In addition to what other answers say you have to account for Visual C++ 10 runtime heap being thread-safe. This implies that even when you only have one thread you encounter some overhead facilitating heap operations being thread-safe. So one reason you see such poor results is that you use a universal but rather slow heap implementation.
The reason why you get different timing with/without the debugger is a special heap is used when a program is started under debugger (even in Release configuration) and that special heap is also relatively slow.