▶ CPU - GPU 异步操作

▶ 源代码

 #include <stdio.h>
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
#include <helper_cuda.h>
#include <helper_functions.h> __global__ void increment_kernel(int *g_data, int inc_value)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
g_data[idx] = g_data[idx] + inc_value;
} bool correct_output(int *data, const int n, const int x)
{
for (int i = ; i < n; i++)
{
if (data[i] != x)
{
printf("Error! data[%d] = %d, ref = %d\n", i, data[i], x);
return false;
}
}
return true;
} int main(int argc, char *argv[])
{
printf("Start.\n");
int devID = findCudaDevice(argc, (const char **)argv); // 通过命令行参数选择设备,可以为空
cudaDeviceProp deviceProps;
cudaGetDeviceProperties(&deviceProps, devID);
printf("CUDA device [%s]\n", deviceProps.name); const int n = * * ;
const int nbytes = n * sizeof(int);
const int value = ; int *a, *d_a;
cudaMallocHost((void **)&a, nbytes);
cudaMalloc((void **)&d_a, nbytes);
memset(a, , nbytes);
cudaMemset(d_a, , nbytes); cudaEvent_t start, stop; // GPU 端计时器
cudaEventCreate(&start);
cudaEventCreate(&stop); StopWatchInterface *timer = NULL; // CPU 端计时器
sdkCreateTimer(&timer);
sdkResetTimer(&timer); dim3 threads = dim3(, , );
dim3 blocks = dim3(n / threads.x, , ); sdkStartTimer(&timer); // 注意 GPU 计时器是夹在 CPU 计时器内的,但是 GPU 函数都是异步的
cudaEventRecord(start, );
cudaMemcpyAsync(d_a, a, nbytes, cudaMemcpyHostToDevice, );
increment_kernel << <blocks, threads, , >> > (d_a, value);
cudaMemcpyAsync(a, d_a, nbytes, cudaMemcpyDeviceToHost, );
cudaEventRecord(stop, );
sdkStopTimer(&timer); unsigned long int counter = ; // 记录 GPU 运行完成以前 CPU 运行了多少次 while 的循环
while (cudaEventQuery(stop) == cudaErrorNotReady)
counter++; float gpu_time = 0.0f; // 此时保证 GPU 运行完成,才能记录时间
cudaEventElapsedTime(&gpu_time, start, stop); printf("time spent by GPU: %.2f\n", gpu_time);
printf("time spent by CPU: %.2f\n", sdkGetTimerValue(&timer));
printf("CPU executed %lu iterations while waiting for GPU to finish\n", counter);
printf("\n\tFinish: %s.", correct_output(a, n, value) ? "Pass" : "Fail"); cudaEventDestroy(start);
cudaEventDestroy(stop);
cudaFreeHost(a);
cudaFree(d_a);
getchar();
return ;
}

● 输出结果:

GPU Device : "GeForce GTX 1070" with compute capability 6.1

CUDA device [GeForce GTX ]
time spent by GPU: 11.50
time spent by CPU: 0.05
CPU executed iterations while waiting for GPU to finish Finish!

▶ 新姿势:

● 调用主函数时的第0个参数作为程序名字符串,可以用于输出。

 int main(int argc, char *argv[])
...
printf("%s", argv[]);

● 在没有附加 flag 的情况下申请主机内存,注意使用cudaFreeHost释放

 int *a, nbytes = n * sizeof(int);
cudaMallocHost((void **)&a, nbytes);
...
cudaFreeHost(a);

● 记录 CPU 调用 CUDA 所用的时间

 StopWatchInterface *timer = NULL;
sdkCreateTimer(&timer);
sdkResetTimer(&timer);
sdkStartTimer(&timer); ...// 核函数调用 sdkStopTimer(&timer);
printf("%.2f ms", sdkGetTimerValue(&timer));

● 查看GPU队列状态的函数

extern __host__ cudaError_t CUDARTAPI cudaEventQuery(cudaEvent_t event);

■ stop为放置到流中的一个事件,cudaEventQuery(stop)返回该事件的状态,等于cudaSuccess(值等于0)表示已经发生;等于cudaErrorNotReady(值等于35)表示尚未发生。源代码中利用这段时间让CPU空转,记录了迭代次数。

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

● stdlib.h 中关于返回成功和失败的宏

 #define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

● 示例文件中的错误检查函数(定义在helper_cuda.h中),报告出错文件、行号、函数名,并且重启cudaDevice。

 #define checkCudaErrors(val)  check((val), #val, __FILE__, __LINE__)

 template< typename T >
void check(T result, char const *const func, const char *const file, int const line)
{
if (result)
{
fprintf(stderr, "CUDA error at %s:%d code=%d(%s) \"%s\" \n",
file, line, static_cast<unsigned int>(result), _cudaGetErrorEnum(result), func);
DEVICE_RESET// Make sure we call CUDA Device Reset before exiting
exit(EXIT_FAILURE);
}
} #define DEVICE_RESET cudaDeviceReset();

0_Simple__asyncAPI的更多相关文章

随机推荐

  1. 浅析Spring MVC工作机制

    1.如何使用Spring MVC? 在web.xml中配置一个DispatcherServlet DispatchServlet初始化的时候会去寻找一个在应用程序的WEB-INF目录下的配置文件,命名 ...

  2. 安装myeclipse2015 stable 3.0破解之后发生出现SECURITY ALERT:iNTEGRITY CHECK ERROR然后闪退解决方案

    安装好myeclipse2015 stable以后也一步步按着破解文件的步骤来进行.打开myEclipse---->Subscription information--->Subscrip ...

  3. 什么是PWM信号

    PWM信号脉宽调制PWM是开关型稳压电源中的术语.这是按稳压的控制方式分类的,除了PWM型,还有PFM型和PWM.PFM混合型.脉宽宽度调制式(PWM)开关型稳压电路是在控制电路输出频率不变的情况下, ...

  4. D. How many trees? DP

    D. How many trees? time limit per test 1 second memory limit per test 64 megabytes input standard in ...

  5. Python协程爬取妹子图(内有福利,你懂得~)

    项目说明: 1.项目介绍   本项目使用Python提供的协程+scrapy中的选择器的使用(相当好用)实现爬取妹子图的(福利图)图片,这个学会了,某榴什么的.pow(2, 10)是吧! 2.用到的知 ...

  6. spring框架总结(04)----介绍的是Spring中的JDBC模板

    1.1  Jdbc模板概述 它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装.spring框架为我们提供了很多的操作模板类,入下图所示: 我们今天的主角在spring-jd ...

  7. 替代PhotoShop:GIMP图形编辑器的使用

    GIMP最早是linux环境下用于图形编辑的一款开源软件,目前的功能很已经很丰富,如果使用得当,在很多的图形编辑操作上完全可以替代收费的Photoshop(PS).目前GIMP已经发展成了多平台的开源 ...

  8. MySQL笔记 存储过程 游标 触发器

    第二十三章 使用存储过程 MySQL5 中添加了存储过程的支持. 大多数SQL语句都是针对一个或多个表的单条语句.并非所有的操作都怎么简单.经常会有一个完整的操作需要多条才能完成 存储过程简单来说,就 ...

  9. IsKeyboardFocused -- 键盘焦点

    <Trigger Property="IsKeyboardFocused" Value="true"> <!--<Setter Prop ...

  10. C# 复制列表

    本文:如何复制一个列表 最简单的方法是 foreach foreach(var temp in a) { b.Add(temp); } 有没一个简单的方法? using System.Linq; va ...