std::sort vs. list::sort

Started by
8 comments, last by iMalc 10 years, 11 months ago

I wanted to do a quick performance (very unscientific though) test on std::vector and std::list and I was very surprised by the results. Maybe it's just me not understanding or knowing how each implements everything internally.

My surprise came when I sorted a vector vs. sorted a equally size linked list. I understand that std::sort requires a random access iterator that std::list doesn't provide which is why their is a list::sort method. Though I thought that using std::sort would require a swap internally (not sure why I do think that, I'm sure I should be doing more research about the internals of each) which wold require each and every object to be copied over. Now the test object I use is just a very basic struct that "simulates" a Rectangle that has a length, width, x position, and y position, all stored as doubles. I overloaded the < operator in it to do the sort and it should sort it based on area (just went ahead and calculated the length*width instead of storing an area member variable, not trying to make this scientific or find performances).

In my test I store 1,000,000 rectangles in a vector a list and set the length, width, xPosition, and yPosition to random numbers for each element in the vector. I then set each elements length, width, xPosition, and yPosition in the list to the vectors corresponding element. Calculate the time for each. Maybe I should use a more scientific approach to this, as I am only using std::clock_t and CLOCKS_PER_SEC to calculate.

When doing this I am very surprised at the performance gap between the two!

First, here's my code to do this quick test, although it isn't anything special or scientific


// Tests Sorting Lists and Vectors Performance

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <ctime>

struct Rectangle
{
	double length;
	double width;
	double xPosition;
	double yPosition;

	bool operator<(const Rectangle& rect) const
	{
		return (length*width) < (rect.length*rect.width);
	}
};

int main()
{
	const int NUM_ELEMENTS = 1000000;
	std::clock_t startTime;
	std::clock_t stopTime;

	std::vector<Rectangle> myVector(NUM_ELEMENTS);
	std::vector<Rectangle>::iterator vectIter;

	// Insert rectangle data in vector
	startTime = clock();
	for(vectIter = myVector.begin(); vectIter != myVector.end(); ++vectIter)
	{
		vectIter->length = 1.0*rand()/RAND_MAX;
		vectIter->width = 1.0*rand()/RAND_MAX;
		vectIter->xPosition = 1.0*rand()/RAND_MAX;
		vectIter->yPosition = 1.0*rand()/RAND_MAX;
	}
	stopTime = clock();
	double totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
	std::cout << "Inserted rectangles in vector in: " << totalTime <<std::endl;

	std::list<Rectangle> myList(NUM_ELEMENTS);
	std::list<Rectangle>::iterator listIter;

	// Insert rectangle data in list
	startTime = clock();
	for(vectIter = myVector.begin(), listIter = myList.begin(); listIter != myList.end() && vectIter != myVector.end(); ++listIter, ++vectIter)
	{
		listIter->length = vectIter->length;
		listIter->width = vectIter->width;
		listIter->xPosition = vectIter->xPosition;
		listIter->yPosition = vectIter->yPosition;
	}
	stopTime = clock();
	totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
	std::cout << "Inserted rectangles in list in: " << totalTime <<std::endl;

	// sort the vector using std::sort algoorithm
	startTime = clock();
	std::sort(myVector.begin(), myVector.end());
	stopTime = clock();
	totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
	std::cout << "Time for sorting a vector: " << totalTime << std::endl;

	// sort the list
	// can't use std::sort, use the list member function
	startTime = clock();
	myList.sort();
	stopTime = clock();
	totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC;
	std::cout << "Time for sorting a list: " << totalTime << std::endl;

	return 0;
} 

The output/performance I get

Inserted Rectangles in Vector in: 1.597

Inserted Rectangles in List in: 2.989

Time for sorting a vector: 3.384

Time for sorting a list: 111.252

What's with the HUGE perforamance decrease in sorting that list? I understand list is slow at random access and that is what std::vector is strong at, but that big a performance hit when using a list? I think list::sort uses a merge sort, which is O(NlogN), I believe. What would std::sort be using in this case? is their any guarantee or way to see what implementation it is using (maybe I didn't research enough), but does the standard guarantee what it will use? Is their a worst case Big-Oh run time that std::sort guarantees? Average Big-Oh run time?

I understand that this isn't a scientific test nor would I use something like that in a real world code, but is their something just crazy wrong with my code that I'm missing that is causing the list to be that much slower? I do still understand where benefits of using a list would come in, but if this is correct I can totally understand why I've always been told "look at std::vector first." Is this correct? Maybe it's because since the object I am sorting in each is very basic and if I was using a larger and more advanced class that would take longer to copy and results could be different?

Interested in any comments on this.

Note: this is just curiosity and I am not trying to pre-optimize current real world code that I have or anything. Just my Computer Science brain being curious.

Advertisement

The standard does not state what algorithm must be used for either std::sort or std::list::sort. It does say, however, that both must complete in O(nlogn) (on average; I'm unsure if the standard states their maximum complexity on worst case execution). From what I've heard, std::sort typically uses intro-sort (which is O(nlogn) in both the average and worst cases). std::list::sort often uses mergesort. Implementations might do some clever modifications to these general algorithms, though, so they may not just be straight implementations of well known algorithms.

There are several things that might contribute to your big discrepancy:

  • Bad compiler options for timing code. If you didn't test "release" code (and instead tested "debug" code), the standard containers might be doing a lot of error checking and validating of iterators. Also, you should consider turning on your compiler's optimization flags so it doesn't generate "dumb" machine code (but if it's too smart, it could optimize too much of your code away and make your timings meaningless).
  • Cache misses. This one can be huge, and it's hard to say exactly when and if it's occurring. Tools like valgrind (if you're not on Windows) can help detect cache misses. std::list doesn't necessarily store the elements in a contiguous array, which could result in some extra cache misses (and in terms of CPU cycles, a cache miss is a big slow down).
  • Usage of std::clock(). std::clock() does not measure "wall clock" time (i.e. what your watch says). It measures "CPU time," which is completely different. While it should work in theory (the difference of two std::clock() calls is supposedly meaningful, compared to the actual value of an individual call), it's not the best way to really profile your code (CPU sampling with a proper profiler (like Visual Studio's) is far more effective).
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
IIRC, the algorithmic performance guarantees of std::sort are the same as quicksort.

As for the performance difference, it's likely got nothing to do with algorithms, but realities of hardware. The CPU cache likes vectors and hates lists ;)
I imagine that if you run your code through a profiler and check the number of cache misses between the two sorting functions, it would go a long way to explaining the discrepancy.

I was just thinking about the cache misses when I was thinking that the std::list doesn't have to store the elements contiguously. I did a bit more research and it seems the performance difference is more than likely hardware and cache misses with the std::list.

Thanks!

Even if the list does miraculously store it's elements contiguously, it's still got the overhead of the next/prev pointers per node, which in your case for a 32-bit build, is an increase of 25% on the amount of memory that has to be moved from RAM to cache to RAM. CPUs have gotten so fast these days that many simple algorithms will be completely bottlenecked by memory access times.

Out of interest, you may want to run your tests again using floats and/or shorts and/or bytes for the Rectangle's members, and seeing if it affects the performance of the sort.

I just ran the code to see what the results are in my machine, I am using mingw with gcc 4.7.1,

Debug mode :

Inserted rectangles in vector in: 0.072

Inserted rectangles in list in: 0.058

Time for sorting a vector: 0.53

Time for sorting a list: 0.916

Release Mode:

Inserted rectangles in vector in: 0.056

Inserted rectangles in list in: 0.016

Time for sorting a vector: 0.234

Time for sorting a list: 0.415

So, not much of a difference in my machine though

While we're at it, here are some clang++3.2 (Apple 4.2) results (I removed the "insertion" timings because it's not a fair test (inserting to the vector calls rand() and converts the int to double, whereas the list just copies a double)):

No optimizations, default standard library:

Time for sorting a vector: 0.388013
Time for sorting a list: 0.768855
No optimizations, libc++ library:
Time for sorting a vector: 0.258923
Time for sorting a list: 0.696469
O3 optimizations and NDEBUG, default standard library:
Time for sorting a vector: 0.091026
Time for sorting a list: 0.353424
O3 optimizations and NDEBUG, libc++ standard library:
Time for sorting a vector: 0.091312
Time for sorting a list: 0.309724

Running on Intel Core i7 2.7GHz with 256 KB L2 cache (per core) and 6 MB L3 cache.

Running it with long double gave slightly higher numbers (libc++, no optimizations):

Time for sorting a vector: 0.457013

Time for sorting a list: 0.760925

While running with char gave lower numbers (libc++, no optimizations):

Time for sorting a vector: 0.010401
Time for sorting a list: 0.13561
Indeed, I would blame your differences primarily on the cache.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

This was using Visual Studio 2012. Previous results were from debug build. I never did post my results from a release build, with default optimization.

Release Build:

Time for sorting a vector: 0.136

Time for sorting a list: 0.455

When switching to a char, I get:

Time for sorting a vector: 0.002

Time for sorting a list: 0.045

This is on a Intel Core i7 6MB L3 Cache 2.3 GHz with 3.3 GHz Max Turbo (when program runs, speed jumped to 3.1 GHz until I closed it)

So seems like it Visual Studio 2012's Compiler is doing some heavy checking when compiled in Debug Mode

Tried it using highest optimization level and favoring speed in Visual Studio and results were pretty much exactly the same. I would need to use a profiler if I wanted to start studying some differences more.

I would say this could also go and show the differences between debug and release builds.

Cornstalks: yea the time for the insertion wasn't fair. I just did that really just to do it. I wasn't really studying that nor basing the list results or vector results based on that.

Profiling debug builds is generally a complete waste of time.

This was using Visual Studio 2012. Previous results were from debug build. I never did post my results from a release build, with default optimization.

Release Build:

Time for sorting a vector: 0.136

Time for sorting a list: 0.455

So the results are within a factor of 4. This matches my expectations.

"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement