何时调用cudaDeviceSynchronize? [英] When to call cudaDeviceSynchronize?

查看:290
本文介绍了何时调用cudaDeviceSynchronize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时真正调用 cudaDeviceSynchronize 函数?

据我从CUDA文档中了解,CUDA内核是异步的,因此看来我们应该调用 cudaDeviceSynchronize 每次启动内核后。但是,我尝试了相同的代码(训练神经网络),有没有任何 cudaDeviceSynchronize ,除了时间测量之前的代码。我发现我得到了相同的结果,但是速度提高了7-12倍(取决于矩阵大小)。

As far as I understand from the CUDA documentation, CUDA kernels are asynchronous, so it seems that we should call cudaDeviceSynchronize after each kernel launch. However, I have tried the same code (training neural networks) with and without any cudaDeviceSynchronize, except one before the time measurement. I have found that I get the same result but with a speed up between 7-12x (depending on the matrix sizes).

因此,问题是在时间测量之外是否有任何理由使用 cudaDeviceSynchronize

So, the question is if there are any reasons to use cudaDeviceSynchronize apart of time measurement.

例如:


  • 从复制数据之前是否需要如果我做矩阵乘法

  • Is it needed before copying data from the GPU back to the host with cudaMemcpy?

将GPU返回主机

If I do matrix multiplications like

C = A * B
D = C * F


我应该在两者之间放置 cudaDeviceSynchronize 吗?

should I put cudaDeviceSynchronize between both?

从我的实验看来,我不是。

From my experiment It seems that I don't.

为什么 cudaDeviceSynchronize 会使程序运行这么慢吗?

Why does cudaDeviceSynchronize slow the program so much?

推荐答案

尽管CUDA内核启动是异步的,但所有与GPU相关的任务放在一个流中(这是默认行为)是按顺序执行的。

Although CUDA kernel launches are asynchronous, all GPU-related tasks placed in one stream (which is the default behavior) are executed sequentially.

因此,例如,

kernel1<<<X,Y>>>(...); // kernel start execution, CPU continues to next statement
kernel2<<<X,Y>>>(...); // kernel is placed in queue and will start after kernel1 finishes, CPU continues to next statement
cudaMemcpy(...); // CPU blocks until memory is copied, memory copy starts only after kernel2 finishes

之后才开始复制不需要 cudaDeviceSynchronize 。但是,对于调试以检测哪个内核引起了错误(如果有)是有用的。

So in your example, there is no need for cudaDeviceSynchronize. However, it might be useful for debugging to detect which of your kernel has caused an error (if there is any).

cudaDeviceSynchronize 可能会导致速度变慢,但7-12倍似乎太多了。时间测量可能存在一些问题,或者内核确实非常快,并且显式同步的开销相对于实际计算时间而言是巨大的。

cudaDeviceSynchronize may cause some slowdown, but 7-12x seems too much. Might be there is some problem with time measurement, or maybe the kernels are really fast, and the overhead of explicit synchronization is huge relative to actual computation time.

这篇关于何时调用cudaDeviceSynchronize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆