Consider the following code snippet:
#include <iostream> #include <ctime> #include <vector> #include <list> using namespace std; #define NUM_ITER 100000 int main() { clock_t t = clock(); std::list< int > my_list; std::vector< std::list< int >::iterator > list_ptr; list_ptr.reserve(NUM_ITER); for(int i = 0; i < NUM_ITER; ++i) { my_list.push_back(0); list_ptr.push_back(--(my_list.end())); } while(my_list.size() > 0) { my_list.erase(list_ptr[list_ptr.size()-1]); list_ptr.pop_back(); } cout << "Done in: " << 1000*(clock()-t)/CLOCKS_PER_SEC << " msec!" << endl; }
When I compile and run it using visual studio, all optimizers are turned on, I get the output:
Completed: 8 ms!
When I compile and run it using g ++ using flags
g ++ main.cpp -pedantic -O2
I get a conclusion
Done at: 7349 ms!
Shortly 1000 times slower. Why is this? According to "cppreference", deleting a call in the list should use only constant time.
The code was compiled and executed on the same computer.
c ++ optimization visual-studio stl g ++
Listing
source share