首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >boost.compute使用gpu计算(c++)

boost.compute使用gpu计算(c++)

作者头像
sofu456
发布2022-05-06 15:46:47
发布2022-05-06 15:46:47
1.5K00
代码可运行
举报
文章被收录于专栏:sofu456sofu456
运行总次数:0
代码可运行

boost.compute

https://github.com/boostorg/compute

编译错误

  • cl.h找不到

下载opencl的头文件,icd(源码)和demo https://gitee.com/zhanghe666/OpenCL-Headers.git https://gitee.com/zhanghe666/OpenCL-ICD-Loader.git https://gitee.com/greatpanc/OpenCL-CLHPP-GitHub.git

  • min、max函数找不到

#include <boost/compute.hpp> 头文件放在最上面,避免boost内部其他模块导致函数找不到

demo

代码语言:javascript
代码运行次数:0
运行
复制
compute::device gpu = compute::system::default_device();
// create a compute context and command queue
compute::context ctx(gpu);
compute::command_queue queue(ctx, gpu);
// generate random numbers on the host
std::vector<float> host_vector(1000000);
std::generate(host_vector.begin(), host_vector.end(), rand);
// create vector on the device
compute::vector<float> device_vector(1000000, ctx);
// copy data to the device
compute::copy(host_vector.begin(), host_vector.end(), device_vector.begin(), queue);
// sort data on the device
compute::sort(device_vector.begin(), device_vector.end(), queue);
// copy data back to the host
compute::copy(device_vector.begin(), device_vector.end(), host_vector.begin(), queue);

boost.compute自定义函数

代码语言:javascript
代码运行次数:0
运行
复制
//方法1
boost::compute::function<int (int)> add_four =
    boost::compute::make_function_from_source<int (int)>(
        "add_four",
        "int add_four(int x) { return x + 4; }"
    );
//方法2
BOOST_COMPUTE_FUNCTION(int, add_four, (int x),
{
    return x + 4;
});
//
boost::compute::transform(input.begin(), input.end(), output.begin(), add_four, queue);   //input、output参数传递

opencl自定义函数核函数限定

所有核函数返回都是void

  • _host_,cpu函数,不加标注默认都是该类型函数
  • _kernel_,设备上执行,设备上调用,异步执行
  • _global_,设备上执行,主机cpu上调用函数,异步执行
代码语言:javascript
代码运行次数:0
运行
复制
__global__ void fun(void)
{
    int a=3;
    printf("%d\n", a);
    fun1();
    printf("hello world from GPU\n");
}
int main()
{
    fun<<<1,2>>>();//(grid,block)线程布局,1个块grid,2个线程
	clEnqueueNDRangeKernel(command1,fun1); 
	clfinish(command1); //阻塞等待返回
}

opencv加速

opencv编译参数,with_opencl自动连接opencl的库加速opencv计算

自定义函数遍历像素,可以使用openmp(cpu多线程)或者opencl(gpu异步)加速算法执行。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • boost.compute
  • demo
  • boost.compute自定义函数
  • opencl自定义函数核函数限定
  • opencv加速
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档