Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector::clear() cost so much time?

I ran a profiler (very sleepy) on my program and it shows a high percentage on my reset function (the reset function runs per-frame). The programs looks like this:

Init Section:

std::vector<std::vector<int>> VecOfVecOfPath;
VecOfVecOfPath.resize(20); 
for(int i=0; i<20; i++) VecOfVecOfPath.reserve(640);

VecOfVecOfPath is a series of path found by other functions. VecOfVecOfPath[i] will be filled during execution, per-frame. E.g. It is push_back-ed by other functions, and reset before using, per-frame.

The reset function:

void Reset()
{
for(int i=0; i<20; i++) VecOfVecOfPath[i].clear();
}

So the reset is very simple, but it do have a pretty high ranking in profiler.

Is this common? Does vector::clear() do have such overheads even for built-in type vectors?

Thanks!


I tried build the program in Release mode and then the cost reduced to almost zero. From 12~13% to 0.03~0.04%.

Then I went to the source code of and there are defines like ITERATOR_DEBUG_LEVEL effecting extra operations in Debug mode.

So it is like @noggin182 suggested, things are different in Debug and Release mode.

Quote: "Meke sure you are profiling in release build and search to see if there are any preprocessor conditional defines you set to boost performance. – noggin182 Jan 3 at 15:32"

like image 583
Marson Mao Avatar asked Jan 03 '12 14:01

Marson Mao


1 Answers

It depends on what is in your vector, if your nested vectors contain classes then you will be invoking the d'tor for each instance in the nested vectors. I'm quite sure it will also be deallocating memory.

It sounds like you are writing a game? If so a few books (PDFs) I've read on game writing suggest that vector is good for general use but you will be better off NOT using it for games. Just use native arrays and manage the memory yourself or roll your own container class.

Is 640 the upper-bound of your vector? Would you be better of perhaps using something like this?

sometype Values[20][640];
int size[20];

Then your reset call could just be

for(int i=0; i<20; i++) size[0] = 0;

You will still even be able to use any stl functions like this:

std::sort(Values[i], Values[i] + size[i]);

That's about as much help as I can provide without any more information

like image 111
noggin182 Avatar answered Oct 07 '22 21:10

noggin182