The Next Week: We can use std::nth_element
instead of std::sort
for more efficient BVH Construction
#1328
Milestone
std::nth_element
instead of std::sort
for more efficient BVH Construction
#1328
In Section 3: Bounding Volume Hierarchies of "Ray Tracing: The Next Week", the given approach for splitting BVH volumes is as follows (emphasis mine):
and the general code is
However, if the goal is just to split
objects[start..end)
into a smaller and larger half, we can use the more-efficient standard library algorithmstd::nth_element
, which runs in linear time on average, rather than the linearithmic time complexity ofstd::sort
. The modified code would beConceptually, what
std::nth_element(objects.begin() + start, objects.begin() + mid, objects.begin() + end);
does is it rearranges elements in the range fromobjects.begin() + start
toobjects.begin() + end
(excluding the end, as usual) to ensure thatobjects.begin() + mid
will end up with the value that it would have had if we just sorted the range, and that all elements occurring beforeobjects.begin() + mid
are not greater than it. This is exactly what we want.Admittedly, any actual performance gain from this is probably very small, unless an immense amount of objects are being rendered (I've tested it on my machine with no noticeable differences). However, I think it's a good use of the C++ standard algorithms library, and it doesn't spend time doing what doesn't need to be done.
The text was updated successfully, but these errors were encountered: