编辑:永远不要使用DEBUG构建进行分析...一旦切换到RELEASE,就没有明显的延迟,并且时间呈线性变化。创建和删除1000000个对象的时间总计在370毫秒内。
-
我有一个包含指向对象指针的地图:std::map<int, DummyObject *> myMap
当我删除地图时,我注意到地图越大似乎需要更长的时间 - 指数级。我期待线性行为。
虽然通过地图进行干式迭代(实际上没有做任何事情)的行为或多或少是线性的,但删除对象(不修改地图!!)完全打破了。有没有人对这种行为有解释?更重要的是:我能做些什么来加快速度?因为不幸的是我真的有一个60000+对象的案例,清理我的地图花了太长时间......
以下是代码:
class DummyObject
{
public:
DummyObject() {}
~DummyObject() {}
};
void testSpeed( int iMapSize )
{
const unsigned int uiStart = GetTickCount();
typedef std::map<int, DummyObject *> T_MyMap;
T_MyMap myMap;
// Fill the map...
for( int i = 0; i < iMapSize; i++ ) {
myMap[i] = new DummyObject();
}
const unsigned int uiFilled = GetTickCount();
// Dry iteration through the map...
for( T_MyMap::const_iterator it = myMap.begin(); it != myMap.end(); it++ ) {
int i = 0; // do something
}
const unsigned int uiIterate = GetTickCount();
// Delete the map...
for( T_MyMap::const_iterator it = myMap.begin(); it != myMap.end(); it++ ) {
delete it->second;
}
const unsigned int uiDeleted = GetTickCount();
myMap.clear();
const unsigned int uiCleared = GetTickCount();
DebugText( arg( "MapSize: %1 --- ", iMapSize )
+ arg( "filled: %1 msecs; ", uiFilled - uiStart )
+ arg( "iterate: %1 msecs; ", uiIterate - uiFilled )
+ arg( "deleted: %1 msecs; ", uiDeleted - uiIterate )
+ arg( "cleared: %1 msecs; ", uiCleared - uiDeleted )
+ arg( "total: %1 msecs; ", uiCleared - uiStart ) );
}
我称之为......
testSpeed( 100 );
testSpeed( 1000 );
testSpeed( 10000 );
testSpeed( 100000 );
testSpeed( 1000000 );
...这是我得到的输出:
MapSize: 100 --- filled: 0 msecs; iterate: 0 msecs; deleted: 16 msecs; cleared: 0 msecs; total: 16 msecs;
MapSize: 1000 --- filled: 31 msecs; iterate: 0 msecs; deleted: 15 msecs; cleared: 0 msecs; total: 46 msecs;
MapSize: 10000 --- filled: 203 msecs; iterate: 16 msecs; deleted: 47 msecs; cleared: 15 msecs; total: 281 msecs;
MapSize: 100000 --- filled: 2527 msecs; iterate: 250 msecs; deleted: 1435 msecs; cleared: 234 msecs; total: 4446 msecs;
MapSize: 1000000 --- filled: 34055 msecs; iterate: 2652 msecs; deleted: 172241 msecs; cleared: 1981 msecs; total: 210929 msecs;