From c8be8496c8a15d0ede8338939a7512109b8e5e46 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 27 Nov 2024 13:41:09 -0800 Subject: Initial commit. --- hello/CMakeLists.txt | 11 ++++++++++ hello/hello.cu | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 hello/CMakeLists.txt create mode 100644 hello/hello.cu (limited to 'hello') diff --git a/hello/CMakeLists.txt b/hello/CMakeLists.txt new file mode 100644 index 0000000..e4b4acc --- /dev/null +++ b/hello/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.28) + +project(cuda_hello LANGUAGES CUDA CXX) + +add_executable(cuda_hello + hello.cu) + +# -Wpedantic causes warnings due to nvcc emitting non-standard (gcc-specific) +# host code. +# https://stackoverflow.com/questions/31000996/warning-when-compiling-cu-with-wpedantic-style-of-line-directive-is-a-gcc-ex +target_compile_options(cuda_hello PRIVATE -Wall -Wextra -Wno-pedantic) diff --git a/hello/hello.cu b/hello/hello.cu new file mode 100644 index 0000000..691b18c --- /dev/null +++ b/hello/hello.cu @@ -0,0 +1,59 @@ +#include + +void logDevices() { + int count; + if (cudaGetDeviceCount(&count) != cudaSuccess) { + printf("No CUDA devices found\n"); + return; + } + + printf("CUDA devices found: %d\n", count); + for (int i = 0; i < count; ++i) { + cudaDeviceProp properties; + if (cudaGetDeviceProperties(&properties, i) == cudaSuccess) { + printf("Device [%d]: %s\n", i, properties.name); + } + } +} + +__global__ void kernel(int* array, int N) { + for (int i = 0; i < N; ++i) { + array[i] = i; + } +} + +int main() { + logDevices(); + + constexpr int N = 100; + + int* host_array = new int[N]; + int* device_array = nullptr; + bool success = false; + + if (cudaMalloc(&device_array, N * sizeof(int)) != cudaSuccess) { + goto cleanup; + } + + kernel<<<1, 1>>>(device_array, N); + + if (cudaMemcpy( + host_array, device_array, N * sizeof(int), cudaMemcpyDeviceToHost) != + cudaSuccess) { + goto cleanup; + } + + for (int i = 0; i < N; ++i) { + printf("%d ", host_array[i]); + } + printf("\n"); + + success = true; + +cleanup: + delete[] host_array; + if (device_array != nullptr) { + cudaFree(device_array); + } + return success ? 0 : 1; +} -- cgit v1.2.3