• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Chad Smith

std::sort vs. list::sort

9 posts in this topic

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.

Edited by Chad Smith
2

Share this post


Link to post
Share on other sites

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!

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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

Edited by solewalker
0

Share this post


Link to post
Share on other sites

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.
Edited by Cornstalks
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0