你好我是刚学习cuda,我有一个简单的cuda代码:main.cu,cmakelist不知道怎么写才能跑通代码。麻烦指导一下。
我下面给出代码和cmakelists
(1)代码:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <memory.h>
#include <time.h>
#include "helper_timer.h"
global void increment_kernel(int g_data, int inc_value)
{
int idx = blockIdx.xblockDim.x + threadIdx.x;
g_data[idx] = g_data[idx] + inc_value;
}
int correct_output(int data, const int n, const int x)
{
for (int i = 0; i < n; i++)
if (data[i] != x)
return 0;
}
int main(int argc, char argv[])
{
cudaDeviceProp deviceProps;
cudaGetDeviceProperties(&deviceProps, 0);
printf("CUDA device [%s]\n", deviceProps.name);
int n = 16 * 1024 * 1024;
int nbytes = nsizeof(int);
int value = 26;
int a = 0;
cudaMallocHost((void)&a, nbytes);
memset(a, 0, nbytes);
int d_a = 0;
cudaMalloc((void*)&d_a, nbytes);
cudaMemset(d_a, 255, nbytes);
dim3 threads = dim3(512, 1);
dim3 blocks = dim3(n / threads.x, 1);
cudaEvent_t startGPU, stopGPU;
cudaEventCreate(&startGPU);
cudaEventCreate(&stopGPU);
StopWatchInterface *timer = NULL;
sdkCreateTimer(&timer);
sdkResetTimer(&timer);
cudaThreadSynchronize();
float gpu_time = 0.0f;
sdkStartTimer(&timer);
cudaEventRecord(startGPU, 0);
cudaMemcpyAsync(d_a, a, nbytes, cudaMemcpyHostToDevice, 0);
increment_kernel<<<blocks, threads, 0, 0>>>(d_a, value);
cudaMemcpyAsync(a, d_a, nbytes, cudaMemcpyDeviceToHost, 0);
cudaEventRecord(stopGPU, 0);
sdkStopTimer(&timer);
unsigned long int counter = 0;
while (cudaEventQuery(stopGPU) == cudaErrorNotReady)
{
counter++;
}
cudaEventElapsedTime(&gpu_time, startGPU, stopGPU);
printf("time spent executing by the GPU:%.2f\n", gpu_time);
printf("time spent by CPU in CUDA calls:%.8f\n", sdkGetTimerValue(&timer));
printf("GPU execute %d iteration while waiting forGPU to finish\n", counter);
printf("-------------------------------------------------------------------------\n");
if (correct_output(a, n, value))
printf("TEST PASSED\n");
else
printf("Test FAILED\n");
cudaEventDestroy(startGPU);
cudaEventDestroy(stopGPU);
cudaFreeHost(a);
cudaFree(d_a);
getchar();
cudaThreadExit();
return 0;
}
cmakelists:
cmake_minimum_required(VERSION 3.9)
PROJECT(testCUDA LANGUAGES CXX CUDA)
#cuda
#find_package(CUDA REQUIRED)
add_definitions(-DUSE_CUDA)
set(CUDA_INCLUDE_DIRS /usr/local/cuda/include)
set(CUDA_LIBRARY_DIRS /usr/local/cuda/lib64)
include_directories(${CUDA_INCLUDE_DIRS})
link_directories(${CUDA_LIBRARY_DIRS})
include_directories(/home/yjy/NVIDIA_CUDA-10.2_Samples/common/inc)
#add_library(testCUDA main.cu)
add_executable(testCUDA main.cu)
target_link_libraries(testCUDA ${CUDA_LIBRARY_DIRS} -lcudart_static -lstdc++ -lm -lrt -ldl -lpthread)