Runtime
Memory transfer
#include <stdio.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
__global__ void VecAdd(float* A, float* B, float* C, int N)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < N) C[i] = A[i] + B[i];
}
int main()
{
int N = 10;
size_t size = N * sizeof(float);
float *h_A = (float*)malloc(size);
float *h_B = (float*)malloc(size);
float *d_A, *d_B, *d_C;
cudaMalloc(&d_A, size);
cudaMalloc(&d_B, size);
cudaMalloc(&d_C, size);
cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice);
int threadsPerBlock = 256;
int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
VecAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, N);
float *h_C = (float*)malloc(size);
cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost);
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
free(h_A);
free(h_B);
free(h_C);
}c
Error check
#include <cuda_runtime.h>
#include <helper_cuda.h>
int main() {
cudaError_t err = cudaSuccess;
err = cudaMalloc((void**)&d, size);
if (err != cudaSuccess) {
fprintf(stderr, "error code %s\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, numElements);
err = cudaGetLastError();
checkCudaErrors(cudaMalloc(.));
}cpp