讲了CPU和GPU执行时的Overlap(重叠)的问题。先要了解CUDA中的Stream,一个Stream中的操作是由主机代码发布的一系列在设备上发布的操作,必须确保顺序执行。不同的Streams里面的操作可以交叉操作或者并发执行。设备的操作分为数据传输和kernels。
Stream分为default stream和non-defaultstream。当我们没有指定stream时,使用的就是默认stream,否则就是non-default stream。区别是什么呢?
从设备角度来看,默认stream是synchronizing(同步)的,指的是:no operation in the default stream will begin until all previouslyissued operation in any stream on the device have completed, and an operationin the default stream must complete before any other operation(in any stream onthe device)will begin,里面的in anystream 包括default stream和non-default stream。
从主机角度来看,default stream中的数据传输是阻塞,同步的,而non-default stream中的数据传世非阻塞的,不同步的,但是kernels不管是在默认还是非默认的stream中都是非阻塞不同步的。我认为从主机角度的区别在这个例子中是关键。
在default stream中数据传输使用cudaMemcpy,而在non-default stream中使用cudaMemcpyAsync。
这个例子中其他的知识点还有cudaEventRecord和cudaEventQuery的使用,可以查CUDA Toolkit手册。该例子中cudaEventQuery一直查询,等待cudaEventRecord(stop, 0)前面设备中的所有操作都执行完才跳出循环。表达CPU在GPU工作的同时还可以干别的事情。