Your first nvcc program on Colab - SAXPY with error checking and event timing
Colab T4 · freenotebook90 minrequiredGoal · A complete saxpy.cu that compiles with nvcc, checks every API call, times the kernel with CUDA events and reports achieved bandwidth.
- 1On a Colab T4, run !nvcc --version and !nvidia-smi to confirm the toolchain.
- 2Use %%writefile saxpy.cu to write host code that allocates x and y of 1<<26 floats, fills them, copies to the device.
- 3Write the __global__ saxpy kernel with a grid-stride loop; launch with 256 threads per block.
- 4Wrap every cuda* call in a CUDA_CHECK macro that prints cudaGetErrorString and exits; also call cudaGetLastError after the launch.
- 5Record cudaEvent_t before and after the launch, cudaEventSynchronize, compute elapsed ms and GB/s (3 x n x 4 bytes).
- 6Copy y back and verify every element equals a*x+y within 1e-6; print max error.
- 7Compile with !nvcc -arch=sm_75 -O3 saxpy.cu -o saxpy and run; then deliberately pass a block size of 2048 and observe the launch error message.
- Deliverable
- saxpy.cu plus the printed bandwidth and max-error lines.
- Check
- Max error is 0; achieved bandwidth is at least 180 GB/s on a T4; the 2048-thread launch is caught and reported by CUDA_CHECK rather than silently producing garbage.
- Fallback
- Kaggle T4, or compile with nvcc on any rented single GPU; the code is identical.