#include <hip/hip_runtime.h>
#include <stdio.h>
#define CUDA_CHECK(call) do { \
hipError_t() err = (call); \
if (err != cudaSuccess) { \
printf("CUDA error: %s at %s:%d\n", hipGetErrorString(err), __FILE__, __LINE__); \
hipGetLastError(); \
} \
} while (0)
__global__ void fill_kernel(float* data, float value, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
data[i] = value;
}
}
int main(void) {
int device_count = 0;
CUDA_CHECK(hipGetDeviceCount(&device_count));
if (device_count == 0) {
printf("No CUDA devices found.\n");
return 1;
}
for (int dev = 0; dev < device_count; dev++) {
CUDA_CHECK(hipSetDevice(dev));
int current = 0;
CUDA_CHECK(hipGetDevice(¤t));
printf("Using device %d\n", current);
const int N = 1024;
float* d_data = nullptr;
CUDA_CHECK(hipMalloc((void**)&d_data, N * sizeof(float)));
float* h_data = nullptr;
CUDA_CHECK(hipHostMalloc((void**)&h_data, N * sizeof(float), 0));
dim3 grid(N / 256);
dim3 block(256);
hipLaunchKernelGGL(fill_kernel, dim3(grid), dim3(block), 0, 0, d_data, 3.14f, N);
cudaDeviceSynchronize();
CUDA_CHECK(hipMemcpy(h_data, d_data, N * sizeof(float), cudaMemcpyDeviceToHost));
printf("device %d: h_data[0] = %f\n", dev, h_data[0]);
CUDA_CHECK(hipFree(d_data));
cudaFreeHost(h_data);
}
return 0;
}