• 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
cozzie

Sorting a std::vector efficiently

26 posts in this topic

Hi,

 

I would like to know how/ what possibilities I have to rearrange a std::vector, assuming that I know in which order I want the elements to be rearranged. The sorting/ finding out the new order I've already covered and saved in a 'newIndex' int vector.The only possibility I thought of is making a copy of the original vector and then copy it back in the right order, but that feels like a waste of memory/ performance.

 

Can someone give me some directions?

bool CRenderQueue::SortBucketBlended()
{
	if(mEffectDataCreated)
	{
		size_t bucketSize = mRenderBucketBlended.size();

		std::vector<int>	indexTemp;	
		std::vector<int>	orderTemp;	
		std::vector<float>	distToCam;	
		
		indexTemp.resize(bucketSize);
		orderTemp.resize(bucketSize);
		distToCam.resize(bucketSize);

		for(size_t init=0;init<bucketSize;++init) orderTemp[init] = init;
		
		for(size_t renderable=0;renderable<mRenderBucketBlended.size();++renderable)
		{
			indexTemp[renderable] = renderable;
			distToCam[renderable] = mRenderBucketBlended[renderable].DistToCam;
		}

		sort(orderTemp.begin(), orderTemp.end(), [&](int a, int b)
			{ return distToCam[a] > distToCam[b]; });

		std::vector<int> newIndex;
		newIndex.resize(bucketSize);

		for(size_t results=0;results<bucketSize;++results)
			newIndex[results] = indexTemp[orderTemp[results]];

		// re-arrange the blended bucket based on newIndex?

		return true;
	}
	else return false;
}

Edited by cozzie
0

Share this post


Link to post
Share on other sites
  1. Store what needs to be sorted and nothing more.  Certainly not an entire “renderable”.  What is that anyway?  An entire mesh?  A part of a mesh?
  2. Single-responsibility principle.  A render-queue item is specifically designed to be a contextless collection of just the information needed to sort and determine the order of rendering of mesh parts.  It doesn’t know what a texture is, or a shader, mesh, vertex buffer, index buffer, etc.
  3. Never sort a render queue with std::sort().  It is neither stable (most important factor) nor fast enough thanks to pointer function calls on each compare.  Create a templated base class that uses < and == operators within its code and add these as inlined overridden operators to the render-queue item class/structure.
  4. Adding things to the render queue locally and sorting indices between them within that linear section of memory should always outperform a sort that needs to dereference 2 pointers on each compare, especially when what gets swapped is actually a 4-byte integer (no need to swap 64-bit integers just because you promote to 64-bit machines).

 

 

L. Spiro

1

Share this post


Link to post
Share on other sites

 

  1. Store what needs to be sorted and nothing more.  Certainly not an entire “renderable”.  What is that anyway?  An entire mesh?  A part of a mesh?
  2. Single-responsibility principle.  A render-queue item is specifically designed to be a contextless collection of just the information needed to sort and determine the order of rendering of mesh parts.  It doesn’t know what a texture is, or a shader, mesh, vertex buffer, index buffer, etc.
  3. Never sort a render queue with std::sort().  It is neither stable (most important factor) nor fast enough thanks to pointer function calls on each compare.  Create a templated base class that uses < and == operators within its code and add these as inlined overridden operators to the render-queue item class/structure.
  4. Adding things to the render queue locally and sorting indices between them within that linear section of memory should always outperform a sort that needs to dereference 2 pointers on each compare, especially when what gets swapped is actually a 4-byte integer (no need to swap 64-bit integers just because you promote to 64-bit machines).

 

 

L. Spiro

 

 

1) I don't know what the int's mean.  I assumed they were identifiers to renderable objects of some sort.  Its not like it matters...  If we're storing only what needs to be stored, then a unique id (aka a pointer) is sufficient.

 

2) That doesn't really apply here.  If I store id's to items, how is that different from storing pointers (and yes, I know a very complex Component Entity system might require id's, the OPs clearly not working with one...)?

 

3) I don't see why you would need a stable sort, but if you feel it is necessary std::stable_sort can be dropped in just as easily.

 

4) Whether you are storing int's or pointers, its the same thing performance-wise.  If you're sorting on data stored in an object (distance, shader usage, whatever) then you have to look that up somehow in the sort function.  Looking it up through a pointer is at least as fast, if not faster, than any other method.  If you didn't need object data in the sort, then using pointers is no slower.  Granted 64-bit pointers could be slightly slower to sort than pure 32-bit ints... perhaps... but the difference is negligible at best; and again if you have to look up data to do any compare, pointers are your best option.

0

Share this post


Link to post
Share on other sites
#1 and #2 are similar. “Store what you need.”
They are typically ID values, yes, but to shaders, textures, etc. Since a reasonable limit to the number of valid shader ID’s or texture ID’s is 65,535 concurrently, it is reasonable to use only 2-byte ID’s for these, half the bandwidth of a 32-bit pointer. This means on 32-bit systems you can put the ID’s next to each other in RAM and compare 2 at once, increasing the speed of the sort potentially dramatically.

And once again it performs the sort with as little knowledge about any graphics interfaces as possible; it uses the bare minimum of knowledge it needs to access, which is just a set of integral values for this purpose. Pointers would indeed be suitable too, but then you waste at least 16 bits and can compare only 1 structure member at once.

 

3) I don't see why you would need a stable sort, but if you feel it is necessary std::stable_sort can be dropped in just as easily.

  • So that things on top of each other don’t flicker, especially windshields or translucent objects with the same bounding box.
  • I said std::sort() is too slow.  If std::sort() is too slow, of course std::stable_sort() is too slow.  It would be better not to even use a render queue.

4) Whether you are storing int's or pointers, its the same thing performance-wise.

One word refutes this handily: Cache. Read my reply more carefully; I didn’t say talking about storing, I talked about accessing during a sort.
 

Granted 64-bit pointers could be slightly slower to sort than pure 32-bit ints... perhaps... but the difference is negligible at best

You know there is no such thing as negligible slowdown on a render queue right? Its whole purpose is performance.


#5: Render-queue items, which are tiny structures that hold all these ID’s and depth needed for sorting, also has another important feature that makes it necessary to use a separate structure rather than just a pointer to some modularity-breaking class: Pass number.
On multi-pass renders you should submit each pass to the render queue as a separate render-queue item structure, each with the correct shader ID and textures for that pass.
The object will be drawn once for each pass but the shaders will be properly sorted throughout (no behind-the-scenes changes between what should have been 2 objects drawn with the same shader) and overdraw on following passes will be minimized by having those passes delayed until their proper place in the queue.


L. Spiro
0

Share this post


Link to post
Share on other sites

Thanks all, for the valuable feedback.

For context, here's the Q_RENDERABLE struct (basically just some indices):

typedef struct Q_RENDERABLE			// renderable level; for filling render buckets
{
	int	Effect;
	int	Material;
	int	Mesh;
	int	Instance;
	int	Id;		
	float DistToCam;
} Q_RENDERABLE;

I really like the suggestion (LSpiro) to save the 'newIndex' with the sorted order of renderables and use that for rendering. I will simply not only pass the reference to the renderables vector to my draw function, but also the vector containing just the indices. That way there's no copying, sorting etc. needed within the vector of renderables. This also gives me flexibility when later on I'm sorting buckets on other criteria (For example opaque, from near to far to prevent overdraw etc.).

 

Besides this I read a lot of opinion on the way I'm currently 'generating' the newIndex / sorting based on the distToCam.

A few questions on this:

- what's a stable sort? (it has the exact same parameters and syntax and seems perfectly interchangable)

- would it really be worthwhile to create my own sort (like bubble sort or something)

- any other suggestions on how to improve coming to the newIndex?

(I can 'save' a bit my making the 3 vector's members instead of on the stack and do the initial filling just once, don't think that will bring much though)

(I believe using pointers directly to the dists to cam per renderable instead of copying them, doesn't bring much either)

Edited by cozzie
1

Share this post


Link to post
Share on other sites

std::sort() (and friends) using a function callback cannot be faster than a templated inlined sort designed to call < and == operators (I said this already), and a stable sort is required to address temporal coherency.

Both std::sort and std::stable_sort are templated inlined sorts designed to call operator<.  What was your point again?

  • Only when it is a function object.  Function pointers can’t be inlined, and it does work with function pointers: http://www.cplusplus.com/reference/algorithm/sort/

  • Other cases do not inline so well in my experience.

    My case did not inline.
  • It doesn’t matter anyway since you should be sorting indices, which requires you to make your own sort anyway.

As for the sort needing to be stable, I don't get the argument either. The point of a stable sort is that if for example you have a database of people who have a name ("John Smith") and an age ("45 years"), you first sort by name, and then later sort by age. If the sort is stable, this will give a list of people sorted by age, and within each group of people with the same age, names will be sorted alphabetically. That's not what you do in a render queue.

I gave a more applicable description already. Does no one understand temporal coherence as it pertains to the sorted objects in a render queue across frames? I really get tired of repeating myself.
 
 
 
 

If you do for example something like in Lengyel's 6-7 year old blog post

You mean Christer Ericson’s?
 
 
 
 

Sure, if two objects have exactly identical sort keys, it is possible that they end up being rendered in alternating order between different frames, but who cares.

I sure did when one of the model cars I was using had a back windshield with 2 parts with identical bounding boxes (because they aligned exactly with each other all around the borders), making it flicker like mad until I changed to a temporal-coherence-friendly stable sort.
 
 

Bubble sort as such is an ultra poor algorithm, but in this case, it turns out being one of the best solutions.

A bubble sort requires at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more branch mispredictions.
 
 
Is it this difficult to understand that you can reuse the results of the previous frame to improve the performance of a render queue dramatically?  One of the most important things you can do, in fact.
 
 
L. Spiro Edited by L. Spiro
2

Share this post


Link to post
Share on other sites

Never sort a render queue with std::sort().  It is neither stable (most important factor) nor fast enough thanks to pointer function calls on each compare.  Create a templated base class that uses < and == operators within its code and add these as inlined overridden operators to the render-queue item class/structure.


First you were saying std::sort was guaranteed to be too slow because it had to use a function pointer.

Only when it is a function object.  Function pointers can’t be inlined, and it does work with function pointers: http://www.cplusplus.com/reference/algorithm/sort/


Now you're saying that, because std::sort has the option to use a function pointer, even though you don't have to, it's still too slow. Well, ok, I have the option of creating an insertion sort that calls new for every temp variable to go up against your function pointer std::sort. We'll see who can make the slowest straw-man sort.

In my case it was 2.34 times faster in a large scene with about 100 sortable objects, each sorted 3 times for the different passes for shadows and normal rendering.


Without knowing many details about the OP's code, there's no way I would ever come into an argument saying that something is definitely too slow, just because there's some other version that's 2.34 times faster. Maybe his program has 2.34 times as much as yours did to sort. Maybe it has ten times as much time. Maybe it has one tenth. Generally, I'd expect many more situations where either has plenty of time or neither is fast enough, compared to situations where one fits and the other doesn't.
1

Share this post


Link to post
Share on other sites

I'd be tempted to trust you with your experience in working with render queues if it weren't for the fact that you seem to have little experience working with the STL.

Perhaps it is time to write an in-depth article with downloadable source for users to test on their own then, eh?
I’ve already been through all of these render-queue variants on multiple devices and platforms (multiple x86, multiple x64, and various iOS devices).


L. Spiro
2

Share this post


Link to post
Share on other sites


The point of a stable sort is that if for example you have a database of people who have a name ("John Smith") and an age ("45 years"), you first sort by name, and then later sort by age. If the sort is stable, this will give a list of people sorted by age, and within each group of people with the same age, names will be sorted alphabetically.

That's not a stable sort: that's a secondary sort.  A stable sort will preserve the relative order of two items with the same primary sort key.

 

Just, you know, to be pedantic.

0

Share this post


Link to post
Share on other sites
Only when it is a function object.  Function pointers can’t be inlined, and it does work with function pointers: http://www.cplusplus.com/reference/algorithm/sort/

You seem to be using a different standard library than the rest of us (or at least one that's different from mine...), since mine either uses operator< or a comparison function object.

 

But don't mind me, I'm probably using the wrong one.

 

(problem with car windows)
nobody understands stuff

Yup, sorry. Two different, distinct objects occupying the same space in the same time... I already didn't get that one when watching Timecop.

 

My car has a distinct window in the front, and one in the back. No matter how hard I try, I can't get one to move into the other. From a purely practical point of view, I'm not getting the problem.
 

A bubble sort requires at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more branch mispredictions.

One pass of bubble sort has exactly two cache misses since it traverses the data set exactly once, and strictly linearly. At the second cache miss, the hardware prefetcher kicks in.

For random input, it has on the average n/2 branch mispredictions if the compiler doesn't optimize properly, and zero with a compiler that uses CMOV.
In any case, its amortized runtime is constant. You can call it "temporal coherence", if you think that sounds more intelligent, but it's the same thing.

0

Share this post


Link to post
Share on other sites

One pass of bubble sort has exactly two cache misses since it traverses the data set exactly once, and strictly linearly. At the second cache miss, the hardware prefetcher kicks in.
For random input, it has on the average n/2 branch mispredictions if the compiler doesn't optimize properly, and zero with a compiler that uses CMOV.
In any case, its amortized runtime is constant. You can call it "temporal coherence", if you think that sounds more intelligent, but it's the same thing.

Since you like to childishly mangle quotes, be glad Bregma caught the fact that you don’t know what a stable sort is rather than myself. I’d not have been so kind.

However you decided to keep going, and now you’re not just arguing with me but with Wikipedia:


http://en.wikipedia.org/wiki/Bubble_sort#In_practice

Bubble sort is asymptotically equivalent in running time to insertion sort in the worst case, but the two algorithms differ greatly in the number of swaps necessary. Experimental results such as those of Astrachan have also shown that insertion sort performs considerably better even on random lists. For these reasons many modern algorithm textbooks avoid using the bubble sort algorithm in favor of insertion sort.

Bubble sort also interacts poorly with modern CPU hardware. It requires at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more branch mispredictions. Experiments by Astrachan sorting strings in Java show bubble sort to be roughly 5 times slower than insertion sort


 

In any case, its amortized runtime is constant. You can call it "temporal coherence", if you think that sounds more intelligent, but it's the same thing.

No, they are not the same thing.  An amortized constant run-time is the result of temporal coherence.

Frame-to-frame temporal coherence in the case of a render queue means using the sorted results from the previous frame to increase the performance of the sort on the current frame.  By using temporal coherence you typically get the best case O(n) for both bubble sort and insertion sort, resulting in an amortized run-time constant.

 

Now the only question that remains is why you want to stick to a bubble sort so badly.  It sounds as though you just want to argue by this point, especially by how you mangled my quote.

 

 

L. Spiro

Edited by L. Spiro
0

Share this post


Link to post
Share on other sites

To answer the original question: just sort the indices, and use a radix sort. If your indices are 32-bit, you can use a three-pass radix sort with 11-bit buckets that will nicely fit into the CPU's L1 cache.

And you can also make the radix sort benefit from temporal coherence. But even if you don't, it will be much, much faster than a std::sort in comparison.

2

Share this post


Link to post
Share on other sites

 

To answer the original question: just sort the indices, and use a radix sort. If your indices are 32-bit, you can use a three-pass radix sort with 11-bit buckets that will nicely fit into the CPU's L1 cache.

This looks like indeed a nice idea for applying radix sort. There's so few places where it really fits.

 

I couldn't tell whether it's worth the trouble (still always using std::sort, which for anything practical surprisingly turns out just good enough every time, I've never had enough of a justification for actually using radix sort in my entire life), but from playing with it a decade or two ago, I remember that radix sort can easily be 3-4 times faster than e.g. quicksort/introsort.

So if the sort is indeed bottlenecking you out (that is, you don't meet your frame time, and profiling points to the sort), that would probably be a viable option.

 

Slight nitpick, though: One doesn't of course sort the indices, which would be somewhat pointless. You most certainly didn't mean to say that, but it kind of sounded like it.

One sorts the keys (moving indices). Or well, one sorts indices by key, or whatever one would call it.

Which means that most likely, 3 passes won't be enough, sadly (or you need bigger buckets), since you will almost certainly have at least 48 or 64-bit numbers to deal with (except if you have very few passes and render states, and are very unkind to your depth info).

Not using a stable radix sort to save temp memory may be viable (can instead concat the indices like described above if needed, even if this means an extra pass... the storage size difference alone likely outweights the extra pass because of fitting L1).

 

Thanks for pointing out my mistake, yes I wanted to say that one should sort the keys :). What you get back are the indices which are then used to access your data.

 

Fully generic rendering-related data might not fit into a 32-bit key, that's true. But there are certain occasions where 32 bits are more than enough (or even 16 might suffice), e.g. for sorting particles.

As a quick note on performance, sorting 50k particles back-to-front using an ordinary std::sort on 16-bit keys takes 3.2ms on my machine, whereas an optimized radix-sort needs 0.25ms. If all you need to sort are keys that somehow index other data, it's almost always better to just sort that, and correctly index the data on access because this causes much fewer memory accesses during the sort.

1

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