c++ - Why does omitting the push_back make the loop run slower? -
consider program, compiling on cygwin gcc 5.4.0 , command line g++ -std=c++14 -wall -pedantic -o2 timing.cpp -o timing
.
#include <chrono> #include <iostream> #include <string> #include <vector> std::string generateitem() { return "a"; } int main() { std::vector<std::string> items; std::chrono::steady_clock clk; auto start(clk.now()); std::string item; (int = 0; < 3000000; ++i) { item = generateitem(); items.push_back(item); // ********* } auto stop(clk.now()); std::cout << std::chrono::duration_cast<std::chrono::milliseconds> (stop-start).count() << " ms\n"; }
i consistently reported time of around 500 ms. however, if comment out starred line, omitting push_back
vector
, time reported around 700 ms.
why not pushing vector
make loop run slower?
i've run test now, , problem in push_back
version, item
string not being deallocated. changing code to:
#include <chrono> #include <iostream> #include <string> #include <vector> std::string generateitem() { return "a"; } int main() { std::chrono::steady_clock clk; auto start(clk.now()); { std::vector<std::string> items; std::string item; (int = 0; < 3000000; ++i) { item = generateitem(); items.push_back(item); // ********* } } auto stop(clk.now()); std::cout << std::chrono::duration_cast<std::chrono::milliseconds> (stop-start).count() << " ms\n"; }
gives expected behaviour of, on cygwin machine, same time both options, measure deallocations time.
to explain further, original code basically:
allocate items start clock repeat 3000000 times allocate std::string("a") move std::string("a") end of items array stop clock deallocate 3000000 strings
so, performance dominated 3000000 allocations. now, if comment out push_back()
, get:
allocate items start clock repeat 3000000 times allocate std::string("a") deallocate std::string("a") stop clock
now measure 3000000 allocations , 3000000 deallocations, should obvious slower. suggestion moving items
vector deallocation timing span means have either push_back()
:
start clock allocate items repeat 3000000 times allocate std::string("a") move std::string("a") end of items array deallocate 3000000 strings stop clock
or without push_back()
:
start clock allocate items repeat 3000000 times allocate std::string("a") deallocate std::string("a") deallocate empty array stop clock
so, both ways round measure 3000000 allocations , deallocations, code take same time.
Comments
Post a Comment