CUDA中使用thrust进行排序和注意事项

在CUDA中进行排序时,如果用自定义cuda十分耗时,我们选择cuda自定义函数进行测试,选择thrust::sort函数,新建文件,命名为sort.cu,代码如下:

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/generate.h>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <algorithm>
#include <vector>
#include <time.h>

int main(void)
{
    thrust::host_vector<int> h_vec(10000*20);
    std::generate(h_vec.begin(), h_vec.end(), rand);

    std::vector<int> vec(h_vec.size());
    thrust::copy(h_vec.begin(), h_vec.end(), vec.begin());

    thrust::device_vector<int> d_vec=h_vec;
    clock_t time1,time2;

    time1 = clock();
    thrust::sort(d_vec.begin(), d_vec.end());
    time2 = clock();
    std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl;

    time1 = clock();
    std::sort(vec.begin(),vec.end());
    time2 = clock();
    std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl;

    time1 = clock();
    thrust::sort(h_vec.begin(), h_vec.end());
    time2 = clock();
    std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl;

    return 0;
}

新建CMakeLists.txt,添加内容如下:

CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
PROJECT(thrust_examples)
set(CMAKE_BUILD_TYPE Release)
find_package(CUDA)
include_directories(${CUDA_INCLUDE_DIRS})
message(STATUS "${CUDA_INCLUDE_DIRS}")
message(STATUS "${CUDA_LIBRARIES}")
cuda_add_executable(thrust_examples sort.cu)

 注意事项:

1、引用thrust时,一定要写在.cu文件中,并且编译成cuda,详细见:

c++ - Thrust Static Assertion when using in cpp files - Stack Overflow

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值