cuda并行归约算法(不断优化过程)

归约

在这里插入图片描述

方法

在这里插入图片描述

#include<cuda_runtime_api.h>
#include<cuda_runtime.h>
#include<device_launch_parameters.h>
#include<iostream>
#include<device_functions.h>
using namespace std;
__global__ void jia(int a[101], int b[101]) {
   
    __shared__ int sdata[101];
    int idx = threadIdx.x;
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    sdata[idx] = a[x];
    __syncthreads();
    for (int s = 1; s < blockDim.x; s *= 2) {
   
        if (idx % (s * 2) == 0) {
   
            sdata[idx] += sdata[idx + s];
        }
        __syncthreads();
    }
    if (idx == 0)b[0] = sdata[0];
}
int main() {
   
	int ha[101];
    int *da,*db;
    int hb[101];
    for(int i = 0; i <= 100; i++)
            ha[i] = i;


    cudaMalloc((void**)&da, sizeof(int) * 101);
    cudaMalloc((void**)&db, sizeof(int) * 101);
    cudaMemcpy(da, ha, sizeof(int) * 101, cudaMemcpyHostToDevice);
    dim3 Block(101);
    jia << <1, Block >> > (da,db);
    cudaMemcpy(hb, db, sizeof(int), cudaMemcpyDeviceToHost);
    cout << hb[0] << endl;
    cudaFree(da);
    cudaFree(db);
}

优化一

在这里插入图片描述
在上一方法中对于线程的使用由于间隔使用会造成很大的资源浪费

#include<cuda_runtime_api.h>
#include<cuda_runtime.h>
#include<device_launch_parameters.h>
#include<iostream>
#include<device_functions.h>
using namespace std;
__global__ void jia(int a[101], int b[101]) {
   
    __shared__ int sdata[101];
    int idx = threadIdx.x;
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    sdata[idx] = a[x];
    __syncthreads();
    f
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值