当前位置: 首页 > news >正文

CUDA学习笔记08: 原子规约/向量求和

参考资料

CUDA编程模型系列一(核心函数)_哔哩哔哩_bilibili

代码

#include <iostream>
#include <cuda_runtime.h> 
#include <device_launch_parameters.h>
#include <stdio.h>
#include <math.h>#define N 10000000
#define BLOCK 256
#define GRID_SIZE 32__managed__ int source[N];
__managed__ int gpu_result[1] = { 0 };__global__ void sum_gpu(int* in, int count, int* out)
{__shared__ int ken[BLOCK];//grid_loopint shared_tmp = 0;for (int idx = blockDim.x * blockIdx.x + threadIdx.x; idx < count; idx += blockDim.x * gridDim.x){shared_tmp += in[idx];}ken[threadIdx.x] = shared_tmp;__syncthreads();int tmp = 0;for (int total_threads = BLOCK / 2; total_threads >= 1; total_threads /= 2){if (threadIdx.x < total_threads){tmp = ken[threadIdx.x] + ken[threadIdx.x + total_threads];}__syncthreads();if (threadIdx.x < total_threads){ken[threadIdx.x] = tmp;}}// block_sum -> share memory[0]if (blockIdx.x * blockDim.x < count){if (threadIdx.x == 0){atomicAdd(out, ken[0]);// memory space wmr}}}// 规约
void test01()
{int cpu_result = 0;/* 初始化 */for (int i = 0; i < N; i++) {source[i] = rand() % 10;}cudaEvent_t start, stop_cpu, stop_gpu;cudaEventCreate(&start);cudaEventCreate(&stop_cpu);cudaEventCreate(&stop_gpu);cudaEventRecord(start);cudaEventSynchronize(start);for (int i = 0; i < 20; i++) {gpu_result[0] = 0;sum_gpu<<<GRID_SIZE, BLOCK>>>(source, N, gpu_result);cudaDeviceSynchronize();}cudaEventRecord(stop_gpu);cudaEventSynchronize(stop_gpu);for (int i = 0; i < N; i++) {cpu_result += source[i];}cudaEventRecord(stop_cpu);cudaEventSynchronize(stop_cpu);float time_cpu = 0, time_gpu = 0;cudaEventElapsedTime(&time_cpu, stop_gpu, stop_cpu);cudaEventElapsedTime(&time_cpu, start, stop_gpu);printf("CPU time: %.2f\nGPU time: %.2f\n", time_cpu, time_gpu / 20);printf("Result: %s\nGPU_result: %d;\nCPU_result: %d;\n", (gpu_result[0] == cpu_result) ? "Pass" : "Error", gpu_result[0], cpu_result);
}

代码在windows下可以运行.

http://www.lryc.cn/news/326176.html

相关文章:

  • PointNet++论文复现(一)【PontNet网络模型代码详解 - 分类部分】
  • AI渣土车监测报警摄像机
  • Spring框架介绍及详细使用
  • 【论文速读】| 对大语言模型解决攻击性安全挑战的实证评估
  • 小迪安全48WEB 攻防-通用漏洞Py 反序列化链构造自动审计 bandit魔术方法
  • 微服务:解放软件开发的神器,引领企业级应用的未来(二)
  • easyexcel与vue配合下载excel
  • Vue.js 模板语法
  • 信号处理--基于DEAP数据集的情绪分类的典型深度学习模型构建
  • Spring设计模式-实战篇之模板方法模式
  • PTA天梯赛习题 L2-006 树的遍历
  • js相关的dom方法
  • Django——Ajax请求
  • 基于java多角色学生管理系统论文
  • python(django)之单一接口管理功能后台开发
  • 教程1_图像视频入门
  • MQTT.fx和MQTTX 链接ONENET物联网提示账户或者密码错误
  • Svn添加用户、添加用户组、配置项目权限等自动化配置脚本
  • Spring事务-两种开启事务管理的方式:基于注解的声明式事务管理、基于编程式的事务管理
  • OC 技术 苹果内购
  • 云原生周刊:Kubernetes v1.30 一瞥 | 2024.3.25
  • 2016年认证杯SPSSPRO杯数学建模D题(第一阶段)NBA是否有必要设立四分线解题全过程文档及程序
  • EdgeGallery开发指南
  • ubuntu arm qt 读取execl xls表格数据
  • STM32 使用gcc编译介绍
  • FPGA之组合逻辑与时序逻辑
  • git clone没有权限的解决方法
  • Redis 的内存回收策略
  • 小程序富文本图片宽度自适应
  • 安装redis时候修改过的配置文件