Medium
A grid-stride loop launched with far fewer threads than elements
This kernel is launched with only 1024 total threads (gridStride<<<4, 256>>>) to process an array of 10,000,000 elements. What does it compute, and why is this pattern preferred over trying to launch exactly one thread per element?
kernel.cu
__global__ void gridStride(float* out, const float* in, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
for (int i = idx; i < n; i += stride) {
out[i] = in[i] * 2.0f;
}
}20 of 46 in GPU / CUDA