How to sort with less precision on keys with Thrust library

删除回忆录丶 提交于 2019-12-24 13:03:07

问题


I have a set of integer values and I want to sort them using Thrust. Is there a possiblity for using only some high bits/low bits in this sorting. If possible I do not want to use user defined comparator, because it changes the used algorithm from radix-sort to merge-sort and increases elapsed time quite much.

I think when all the numbers have the same value on a bit, the bit is skipped while sorting, so is it feasible to use the lowest possible bit number and hope it will be sufficient. (ie: for 5 bits using char with 8 bits and setting upper 3 bits to 0)

Example:

sort<4, 0>(myvector.begin(), myvector.end())
sort<4, 1>(myvector.begin(), myvector.end())

sort using only 4 bits, high or low..

Something similar to http://www.moderngpu.com/sort/mgpusort.html


回答1:


Thrust's interface abstracts away algorithm implementation details such as the fact that one of the current sorting strategies is a radix sort. Due to the possibility that the underlying sort implementation could change from version to version, backend to backend, or even invocation to invocation, there is no way for the user to communicate the number of bits to sort.

Fortunately, such explicit information generally isn't necessary. When appropriate, Thrust's current sorting implementation will inspect the sorting keys and omit superfluous computation amidst zeroed bits.




回答2:


How about using transformer_iterator? Here is a short example (sort by first bit) and you can write your own unary function for your purpose.

#include <iostream>
#include <thrust/device_vector.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/sort.h>

using namespace std;
struct and_func : public thrust::unary_function<int,int>
{
    __host__ __device__
        int operator()(int x)
        {
            return 8&x;
        }
};
int main()
{
    thrust::device_vector<int> d_vec(4);
    d_vec[0] = 10;
    d_vec[1] = 8;
    d_vec[2] = 12;
    d_vec[3] = 1;
    thrust::sort_by_key(thrust::make_transform_iterator(d_vec.begin(), and_func()),
                 thrust::make_transform_iterator(d_vec.end(), and_func()),
                 d_vec.begin());
    for (int i = 0; i < 4; i++)
        cout<<d_vec[i]<<" ";
    cout<<"\n"<<endl;
    return 0;
}


来源:https://stackoverflow.com/questions/11012040/how-to-sort-with-less-precision-on-keys-with-thrust-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!