Tuesday, March 09, 2010

C++0x tips: improve performance in code using STL containers

Hello, I am hungry for code performance, specially in my simulations involving entire cities full with people, mosquitoes, viruses, homes, flower vases, etc. So it has been frustrating to interrupt the code execution just to realize all it has been doing for hours is creating the cities. Let us examine how the preparation phase takes place:
class houseCls;
class personCls;
//...

class cityCls {
    private:
        vector<houseCls> houses;
        vector<personCls> pedestrians;
    public:
        //...
}

vector<cityCls> country;

int main() {
    for (int i=0; i<nCities; i++)
        country.push_back(cityCls(/* City construction arguments */));
}
On execution, a city is created in the stack, then it is copied into the country vector and then the city in the stack is destroyed. So most runtime is employed in getting the vector ready for simulation. Using an aggregate (array) is out of the question, because things must be dynamic and safety must be ensured in all aspects.
How about just creating the new city in the new space inside the vector? Previously the vector::swap() function helped accomplish this task, but implementation became confuse sometimes for the client programmer.

I took the opportunity to study the improvements of the newest C++ standard, C++0x. I learned about a great STL improvement in terms of memory management, performance, and overall, getting things done. It is the emplace_back() function, which does just what the above question was about.

Use the new C++ standard, at your own risk, taking into account it is evolving.
g++ --pedantic-errors -Wall -Wextra -std=gnu++0x source.cc
Make the following changes to your code:
int main(){
 ///Always reserve memory before starting
 country.reserve(nCities);
 for (int i=0; i<nCities; i++)
  country.emplace_back(/** City construction arguments, which do not need the explicit class name anymore */);
}
You can use explicit copy constructors and gdb to benchmark your code.

No comments:

Post a Comment

Is your comment or question:

1. Constructive?
2. Interesting?
3. Short?

If not, please post it in your own blog.