【CUDA 】-Thrust sort&sortbykey

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include<algorithm>
// includes CUDA
#include <cuda_runtime.h>
#include<device_launch_parameters.h>
// includes, project
#include <helper_cuda.h>
#include <helper_functions.h> // helper functions for SDK examples
//include thrust
#include <thrust/device_ptr.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sort.h>
#include <thrust/copy.h>
using namespace std;
#define N (3)  //每個(gè)對(duì)象的條件屬性個(gè)數(shù)
#define M (12) //保存對(duì)象個(gè)數(shù)
__device__ __managed__ int d_attrSelect[N];//定義全局變量尊浪,保存有效的屬性選擇。
struct Element
{
    int attrval[N];//保存該對(duì)象的所有的條件屬性值
    bool __host__ __device__ operator<(const Element& e)const
    {
        for (int i = 0; i < N; i++)
        {
            if (d_attrSelect[i] == 0)//為0表示該屬性無(wú)效
            {
                continue;
            }
            if (attrval[i]<e.attrval[i])
            {
                return true;
            }
            if (attrval[i]>e.attrval[i])
            {
                return false;
            }
            if (attrval[i] == e.attrval[i])
            {
                continue;
            }
        }
        return false;
    }
    bool __host__ __device__ operator == (const Element & e)const
    {
        bool res = true;
        for (int i = 0; i < N; i++)
        {
            if (d_attrSelect[i] == 0)//如果為0則無(wú)效
                continue;
            if (attrval[i] != e.attrval[i])
            {
                res = false;
                break;
            }
        }
        return res;
    }
};
void Split(const string& src, const string& separator, vector<string>& dest)
{
    string str = src;
    string substring;
    string::size_type start = 0, index;

    do
    {
        index = str.find_first_of(separator, start);
        if (index != string::npos)
        {
            substring = str.substr(start, index - start);
            dest.push_back(substring);
            start = str.find_first_not_of(separator, index);
            if (start == string::npos) return;
        }
    } while (index != string::npos);

    //the last token
    substring = str.substr(start);
    dest.push_back(substring);
}
void InData(const char* fname, thrust::host_vector<Element>&all_elments)
{
#ifdef TIME_TEST
    double timeuse;
    StartTimer();
#endif
    ifstream fin(fname);
    if (!fin)
    {
        // NO, abort program
        cerr << "can't open input file \"" << fname << "\"" << endl;
        getchar();
        exit(EXIT_FAILURE);
    }
    string line;
    string separtor = " ";
    while (getline(fin, line))
    {
        //cout << line << endl;
        Element temp_obj;
        vector<string> temp_string;
        Split(line, separtor, temp_string);

        for (int i = 0; i < temp_string.size(); i++)//去掉最后的決策屬性
        {
            temp_obj.attrval[i] = stoi(temp_string[i]);
            //cout << temp_obj.attrval[i] << "  ";
        }
        //cout << endl;
        all_elments.push_back(temp_obj);
    }
    fin.close();
#ifdef TIME_TEST
    timeuse = GetTimer();
    std::cerr << "[CPU] InData 讀取數(shù)據(jù)的時(shí)間(in second)\t" << timeuse << std::endl;
    StartTimer();
#endif
}
int main()
{
    for (int i = 0; i < N; i++)
    {
        d_attrSelect[i] = 1;
    }
    d_attrSelect[2] = 0;
    for (int i = 0; i <N; i++)
    {
        printf("Host: the value of the global variable is %d\n", d_attrSelect[i]);
    }
    thrust::host_vector <Element> ElementList;
    char s[1024] = "C://Users//hym//Desktop//test.txt";
    InData(s, ElementList);
    cout << " CPU: before sort" << endl;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << ElementList[i].attrval[j] << "  ";
        }
        cout << endl;
        //printf("CPU Sort before:%d %d %d\n", ElementList[i].attrval[0], ElementList[i].attrval[1], ElementList[i].attrval[2]);
    }
    std::sort(ElementList.begin(), ElementList.end());// cpu 串行排序
    thrust::device_vector<Element> dev_element = ElementList;
        thrust::sort(dev_element.begin(), dev_element.end());
        ElementList = dev_element;
    cout << " CPU: After sort" << endl;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << ElementList[i].attrval[j] << "  ";
        }
        cout << endl;
    }
    thrust::host_vector<int> h_value(M);
    for (int i = 0; i < M; i++)
    {
        h_value[i] = i + 1;
    }
    thrust::device_vector<int> d_value = h_value;
    thrust::sort_by_key(dev_element.begin(), dev_element.end(), d_value.begin());
    ElementList = dev_element;
    h_value = d_value;
    for (int i = 0; i < M; i++)
    {
        cout << "id=" << h_value[i] << " ";
        for (int j = 0; j < N; j++)
        {
            cout << ElementList[i].attrval[j] << "  ";
        }
        cout << endl;
    }
    getchar();
    return 0;
}

my test:

0 0 0
0 0 1
1 0 1
1 1 1
0 0 0 
1 1 2
0 0 0 
1 1 1
1 1 2
0 1 1 
1 0 2
1 1 1

最新的cuda中kernel函數(shù)中也可以使用thrust了逼纸。
Thrust inside user written kernels

使用仿函數(shù)進(jìn)行排序

////////////////////////////////////////////////////////////////////////////
//
// Copyright 1993-2015 NVIDIA Corporation.  All rights reserved.
//
// Please refer to the NVIDIA end user license agreement (EULA) associated
// with this source code for terms and conditions that govern your use of
// this software. Any use, reproduction, disclosure, or distribution of
// this software and related documentation outside the terms of the EULA
// is strictly prohibited.
//
////////////////////////////////////////////////////////////////////////////

/* Template project which demonstrates the basics on how to setup a project
* example application.
* Host code.
*/
///*
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include<algorithm>
#include<map>
#include <iomanip>//輸出格式限制
// includes CUDA
#include <cuda_runtime.h>
#include<device_launch_parameters.h>
#include<cusparse.h>
// includes, project
#include <helper_cuda.h>
#include <helper_functions.h> // helper functions for SDK examples
//include thrust
#include <thrust/device_ptr.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/functional.h>
#include <thrust/sequence.h>
#include "basic.h"
using namespace std;
///*
#define N (2)
#define M (12)
#define D (3)
/*/
//*
#define N (16)
#define M (20000)
#define D (26)
//*/
#define TILE_X 8
#define TILE_Y 32
struct Element
{
    int attrval[N];//條件屬性值
    int attrdec;//決策屬性值
};

struct compare_element
{
    thrust::device_vector<int> attr;
    compare_element(thrust::device_vector<int> temp)
    {
        attr = temp;
    }
    __device__ bool operator()(const Element &a, const Element &b)const
    {
        for (int i = 0; i < N; i++)
        {
            if (attr[i] == 0)
            {
                continue;
            }
            if (a.attrval[i]<b.attrval[i])
            {
                return true;
            }
            if (a.attrval[i]>b.attrval[i])
            {
                return false;
            }
            if (a.attrval[i] == b.attrval[i])
            {
                continue;
            }
        }
        return false;
    }
};

void Split(const string& src, const string& separator, vector<string>& dest)
{
    string str = src;
    string substring;
    string::size_type start = 0, index;
    do
    {
        index = str.find_first_of(separator, start);
        if (index != string::npos)
        {
            substring = str.substr(start, index - start);
            dest.push_back(substring);
            start = str.find_first_not_of(separator, index);
            if (start == string::npos) return;
        }
    } while (index != string::npos);

    //the last token
    substring = str.substr(start);
    dest.push_back(substring);
}
void InData(const char* fname, thrust::host_vector<Element>&all_elments)
{
#ifdef TIME_TEST
    double timeuse;
    StartTimer();
#endif
    ifstream fin(fname);
    if (!fin)
    {
        // NO, abort program
        cerr << "can't open input file \"" << fname << "\"" << endl;
        getchar();
        exit(EXIT_FAILURE);
    }
    string line;
    string separtor = " ";
    int obj_cnt = 0;
    while (getline(fin, line) && obj_cnt<M)
    {
        vector<string> temp_string;
        Split(line, separtor, temp_string);
        int length = temp_string.size();
        if ((length - 1) != N)
        {
            cerr << "屬性個(gè)數(shù)不正確:N=" << N << "   實(shí)際的屬性個(gè)數(shù):" << length - 1 << endl;
            getchar();
            exit(EXIT_FAILURE);
        }
        for (int i = 0; i < length - 1; i++)//去掉最后的決策屬性
        {
            all_elments[obj_cnt].attrval[i] = stoi(temp_string[i]);
        }
        all_elments[obj_cnt].attrdec = stoi(temp_string[length - 1]);
        obj_cnt++;
    }
    fin.close();
#ifdef TIME_TEST
    timeuse = GetTimer();
    std::cerr << "[CPU] InData 讀取數(shù)據(jù)的時(shí)間(in second)\t" << timeuse << std::endl;
    StartTimer();
#endif
}


void printData(thrust::host_vector<Element> all_Elements)
{
    cout << "-------------Data------" << endl;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << all_Elements[i].attrval[j] << "   ";
        }
        cout << "   dec=" << all_Elements[i].attrdec << endl;
    }
    cout << endl;
}


int main()
{
    thrust::host_vector<Element> all_Elements(M);//考慮到push_back很慢
    //char s[1024] = "C://Users//hym//Desktop//GPU_Data//letter.txt";//20000 16 26
    char s[1024] = "C://Users//hym//Desktop//GPU_Data//test.txt";//12 2 3
    InData(s, all_Elements);
    printData(all_Elements);
    thrust::device_vector<Element> dev_element = all_Elements;
    thrust::device_vector<int> attr(N, 1);
    compare_element cmp(attr);
    //thrust::sort(dev_element.begin(), dev_element.end(),cmp);
    all_Elements = dev_element;
    printData(all_Elements);
    getchar();
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末阀坏,一起剝皮案震驚了整個(gè)濱河市茵汰,隨后出現(xiàn)的幾起案子奥此,更是在濱河造成了極大的恐慌顿天,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,561評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件腺兴,死亡現(xiàn)場(chǎng)離奇詭異左电,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,218評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門篓足,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)段誊,“玉大人,你說(shuō)我怎么就攤上這事栈拖×幔” “怎么了?”我有些...
    開封第一講書人閱讀 157,162評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵涩哟,是天一觀的道長(zhǎng)索赏。 經(jīng)常有香客問(wèn)我,道長(zhǎng)贴彼,這世上最難降的妖魔是什么潜腻? 我笑而不...
    開封第一講書人閱讀 56,470評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮器仗,結(jié)果婚禮上融涣,老公的妹妹穿的比我還像新娘。我一直安慰自己精钮,他們只是感情好威鹿,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,550評(píng)論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著轨香,像睡著了一般忽你。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上臂容,一...
    開封第一講書人閱讀 49,806評(píng)論 1 290
  • 那天科雳,我揣著相機(jī)與錄音,去河邊找鬼策橘。 笑死炸渡,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的丽已。 我是一名探鬼主播蚌堵,決...
    沈念sama閱讀 38,951評(píng)論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼沛婴!你這毒婦竟也來(lái)了吼畏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,712評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤嘁灯,失蹤者是張志新(化名)和其女友劉穎泻蚊,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體丑婿,經(jīng)...
    沈念sama閱讀 44,166評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡性雄,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,510評(píng)論 2 327
  • 正文 我和宋清朗相戀三年没卸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秒旋。...
    茶點(diǎn)故事閱讀 38,643評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡约计,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出迁筛,到底是詐尸還是另有隱情煤蚌,我是刑警寧澤,帶...
    沈念sama閱讀 34,306評(píng)論 4 330
  • 正文 年R本政府宣布细卧,位于F島的核電站尉桩,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏贪庙。R本人自食惡果不足惜蜘犁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,930評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望插勤。 院中可真熱鬧沽瘦,春花似錦革骨、人聲如沸农尖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,745評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)盛卡。三九已至,卻和暖如春筑凫,著一層夾襖步出監(jiān)牢的瞬間滑沧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,983評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工巍实, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留滓技,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,351評(píng)論 2 360
  • 正文 我出身青樓棚潦,卻偏偏與公主長(zhǎng)得像令漂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子丸边,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,509評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容