Strange running times in C++ loops -




so, i'm writing program, optimization key factor. however: during optimization, notice function considered relatively simple, taking way long run. since, in comparison, more difficult function taking way shorter.

whole relevant section

// simple function  int get_chunk_index(std::vector<chunk> chunks, int x, int y) {     glm::vec3 target = glm::vec3(x * 40, 0, y * 40);     (int = 0; < chunks.size(); i++) {         if (chunks[i].trans.getpos() == target) {             return i;         }     }     return -1; }  // end simple function 

time in function

if more functions, feel free ask, quite large program, can't include everything here.

ps: chunks ever 0->40 in size.

a few simple options.

1) chunks being passed value, creates complete copy of vector being passed. try passing const reference (i.e. const std::vector<chunk> &chunk) instead.

2) rather passing x , y, , creating glm::vec3 (whatever - it's non-standard) them, change function accept glm::vec3 reference. forces caller create object, allows caller control updating of (rather recreating new object every time).

3) take evaluation of chunks.size() out of loop, , use preincrement (won't create temporary) rather post-increment.

std::size_t size = chunks.size(); (int = 0; < size; ++i) {     if (chunks[i].trans.getpos() == target)     {         return i;     } } 

4) consider using iterators rather array indexing.

std::vector<chunk>::const_iterator i, begin = chunks.begin(), end = chunks.end();  (i = begin; != end; ++i)    if (i->trans.getpos() == target) return std::distance(begin, i); 

or (c++11 , later)

for (const auto &i : chunks) {     if (i.trans.getpos() == target) return std::distance(chunks.begin(), i); } 

5) instead of passing vector, pass begin , end iterators. allow more simplification of loop.

6) check getpos() function being called doing, , optimise that.

7) timing measurements optimisation turned on, , them across large number of calls of function. performance measurements of individual function calls don't mean in practice (the jitter in other things affect performance dominate measurements).





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -