ec1117

reduce

Feb 5th, 2026
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include <cuda_runtime.h>
  2.  
  3. __global__ void reduction_kernel(const float* input, float* output, int N) {
  4. // int idx = blockIdx.x * blockDim.x + threadIdx.x;
  5. // if (idx >= N) return;
  6. // atomicAdd(output, input[idx]);
  7. extern __shared__ double sdata[];
  8. int tid = threadIdx.x;
  9. int idx = blockDim.x * blockIdx.x + tid;
  10.  
  11. double local = 0;
  12. if (idx >= N) {
  13. local = 0;
  14. } else {
  15. local = input[idx];
  16. }
  17.  
  18. sdata[tid] = local;
  19.  
  20. for (int s=blockDim.x / 2; s > 0; s >>= 1) {
  21. __syncthreads();
  22.  
  23. if (tid < s) {
  24. sdata[tid] += sdata[tid + s];
  25. }
  26. }
  27.  
  28. __syncthreads();
  29. if (tid == 0) {
  30. // output = sdata[0];
  31. atomicAdd(output, (float) sdata[0]);
  32. }
  33. }
  34.  
  35. // input, output are device pointers
  36. extern "C" void solve(const float* input, float* output, int N) {
  37. int threadsPerBlock = 1024;
  38. int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
  39.  
  40. cudaMemset(output, 0, sizeof(float));
  41.  
  42. reduction_kernel<<<blocksPerGrid, threadsPerBlock, threadsPerBlock * sizeof(double)>>>(input, output, N);
  43. cudaDeviceSynchronize();
  44.  
  45.  
  46. }
  47.  
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment