CUDA sample -asyncAPI

创建一个项目vs项目。

1、配置环境(自己就配置了)

CUDA sample -asyncAPI_第1张图片CUDA sample -asyncAPI_第2张图片

2、因为我们使用了cuda sample中的asyncAPI,所以里面用到了文件夹下comm

CUDA sample -asyncAPI_第3张图片

配置的时候可以参考

CUDA sample -asyncAPI_第4张图片

2、把asyncAPI.cu赋值过来

3、右击asyncAPI.cu

CUDA sample -asyncAPI_第5张图片

4、代码简要分析

__global__ void increment_kernel(int *g_data, int inc_value)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x; // 计算blockId*blockDim+当前线程id
    g_data[idx] = g_data[idx] + inc_value;
}
int n = 16 * 1024 * 1024;
int nbytes = n * sizeof(int);
int value = 26;

// allocate host memory
int *a = 0;
checkCudaErrors(cudaMallocHost((void **)&a, nbytes)); // 分配内存
memset(a, 0, nbytes);// 初始化a为0

// allocate device memory
int *d_a=0;
checkCudaErrors(cudaMalloc((void **)&d_a, nbytes));//分配显存
checkCudaErrors(cudaMemset(d_a, 255, nbytes));//初始化d_a为255

// set kernel launch configuration;设置内核启动配置
dim3 threads = dim3(512, 1);
dim3 blocks  = dim3(n / threads.x, 1);

// create cuda event handles;创建cuda事件句柄
cudaEvent_t start, stop;
checkCudaErrors(cudaEventCreate(&start));
checkCudaErrors(cudaEventCreate(&stop));

StopWatchInterface *timer = NULL;
sdkCreateTimer(&timer);//创建计时器
sdkResetTimer(&timer);//重置计时器

checkCudaErrors(cudaDeviceSynchronize());//cuda同步
float gpu_time = 0.0f;

// asynchronously issue work to the GPU (all to stream 0)
sdkStartTimer(&timer);//计时器开启
cudaEventRecord(start, 0);//记录cuda事件句柄
cudaMemcpyAsync(d_a, a, nbytes, cudaMemcpyHostToDevice, 0); // 将内存数据拷贝到显存
increment_kernel<<>>(d_a, value); // 按照block和threads追加数值
cudaMemcpyAsync(a, d_a, nbytes, cudaMemcpyDeviceToHost, 0); // 将显存拷贝到内存
cudaEventRecord(stop, 0); // 事件记录
sdkStopTimer(&timer); // 计时器终止

// have CPU do some work while waiting for stage 1 to finish
unsigned long int counter=0;

while (cudaEventQuery(stop) == cudaErrorNotReady)
{
    counter++;
}

checkCudaErrors(cudaEventElapsedTime(&gpu_time, start, stop)); // 记录间隔时间

// release resources
checkCudaErrors(cudaEventDestroy(start));
checkCudaErrors(cudaEventDestroy(stop));
checkCudaErrors(cudaFreeHost(a));
checkCudaErrors(cudaFree(d_a));

 

你可能感兴趣的:(cuda,cuda)