Sorting speed of stl vectors and lists
Posted on Friday, February 12 - 2010 (289 words)This snippet is an addition to my previous article about sorting STL containers. I’ve tested the sorting speed of std::vector vs. std::list on my MacBook. As we can see by the results below, vectors are much faster than lists when it comes to sorting (almost 8 times faster on my machine).
Thx to Dean H. for commenting.
| #include <algorithm> // Needed for sort() method
#include <vector> // STL vector class
#include <list> // STL list class
#include <iostream> // Needed for cout,endl
#include <sys/time.h> // Needed for rand,timeval
using namespace std; // Save us some typing
bool comp(const int& num1, const int& num2)
{
return num1 > num2;
}
// Prints the difference between to time values to std::out
void printDiff(const timeval& end, const timeval& start)
{
timeval diff;
diff.tv_sec = end.tv_sec - start.tv_sec;
diff.tv_usec= end.tv_usec - start.tv_usec;
if (diff.tv_usec < 0) {
diff.tv_sec--;
diff.tv_usec += 1000000;
}
cout << "Elapsed time: " << diff.tv_sec << "seconds, "
<< diff.tv_usec << " microseconds." << endl;
}
int main()
{
vector<int> v; // Vector containing integers
vector<int>::iterator vIt; // Iterator navigating through vector
list<int> l; // List containing integers
list<int>::iterator lIt; // Iterator navigating through list
// Insert a 100 million integer values into both containers
srand( time(NULL) ); // Initialize random number generator
generate_n (back_inserter(v), 100000000, rand);
generate_n (back_inserter(l), 100000000, rand);
// Measure sorting time
timeval start, end;
// Sort vector
gettimeofday(&start, 0);
sort(v.begin(), v.end(), comp);
gettimeofday(&end, 0);
cout << "VECTOR: ";
printDiff(end, start);
// Sort list
gettimeofday(&start, 0);
l.sort(comp);
gettimeofday(&end, 0);
cout << "LIST: ";
printDiff(end, start);
/* Output:
* VECTOR: Elapsed time: 99seconds, 566816 microseconds.
* LIST: Elapsed time: 770seconds, 216836 microseconds
*/
return 0;
}
|