Streams and events
A kernel launch returns immediately. So does an asynchronous copy. Streams are how you turn those facts into overlap instead of idle waiting.
Streams are queues#
A CUDA stream is an ordered queue of operations. Work enqueued into one stream runs in order; work in different streams may run concurrently.
cudaStream_t stream;
cudaStreamCreate(&stream);
cudaMemcpyAsync(d_in, h_in, bytes, cudaMemcpyHostToDevice, stream);
kernel<<<grid, block, 0, stream>>>(d_in, d_out);
cudaMemcpyAsync(h_out, d_out, bytes, cudaMemcpyDeviceToHost, stream);
cudaStreamSynchronize(stream); // wait for this stream only
cudaStreamDestroy(stream);The launch syntax grows a third and fourth slot: <<<grid, block, sharedBytes, stream>>>. If you omit the stream, work goes to the default stream.
Operations without a stream are implicitly in the default stream, which is why every example so far has been ordered. The default stream has special semantics: in the legacy model it synchronises with all blocking streams. Create streams with cudaStreamNonBlocking if you want them to ignore the default stream.
Overlap, measured#
This program copies four chunks to the GPU, scales each, and copies them back — first in one stream, then in four. It times both with events.
#include <cstdio>
#include <cuda_runtime.h>
constexpr int N = 1 << 22; // 4M floats = 16 MB
constexpr int CHUNKS = 4;
__global__ void scale(float* data, int n, float factor) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) data[i] *= factor;
}
float runSequential(float* h, float* d, int chunk, int cbytes) {
cudaEvent_t start, stop;
cudaEventCreate(&start); cudaEventCreate(&stop);
cudaEventRecord(start);
for (int c = 0; c < CHUNKS; ++c) {
size_t off = (size_t)c * chunk;
cudaMemcpyAsync(d + off, h + off, cbytes,
cudaMemcpyHostToDevice, 0);
scale<<<chunk / 256, 256, 0, 0>>>(d + off, chunk, 2.0f);
cudaMemcpyAsync(h + off, d + off, cbytes,
cudaMemcpyDeviceToHost, 0);
}
cudaDeviceSynchronize();
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float ms = 0.0f;
cudaEventElapsedTime(&ms, start, stop);
cudaEventDestroy(start); cudaEventDestroy(stop);
return ms;
}
float runStreamed(float* h, float* d, int chunk, int cbytes) {
cudaStream_t s[CHUNKS];
for (int c = 0; c < CHUNKS; ++c) cudaStreamCreate(&s[c]);
cudaEvent_t start, stop;
cudaEventCreate(&start); cudaEventCreate(&stop);
cudaEventRecord(start);
for (int c = 0; c < CHUNKS; ++c) {
size_t off = (size_t)c * chunk;
cudaMemcpyAsync(d + off, h + off, cbytes,
cudaMemcpyHostToDevice, s[c]);
scale<<<chunk / 256, 256, 0, s[c]>>>(d + off, chunk, 2.0f);
cudaMemcpyAsync(h + off, d + off, cbytes,
cudaMemcpyDeviceToHost, s[c]);
}
for (int c = 0; c < CHUNKS; ++c) cudaStreamSynchronize(s[c]);
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float ms = 0.0f;
cudaEventElapsedTime(&ms, start, stop);
for (int c = 0; c < CHUNKS; ++c) cudaStreamDestroy(s[c]);
cudaEventDestroy(start); cudaEventDestroy(stop);
return ms;
}
int main() {
const size_t bytes = N * sizeof(float);
const int chunk = N / CHUNKS;
const int cbytes = chunk * sizeof(float);
float* h;
float* d;
cudaMallocHost((void**)&h, bytes); // pinned: required for async copies
cudaMalloc(&d, bytes);
for (int i = 0; i < N; ++i) h[i] = 1.0f;
float seq = runSequential(h, d, chunk, cbytes);
for (int i = 0; i < N; ++i) h[i] = 1.0f; // reset input
float str = runStreamed(h, d, chunk, cbytes);
printf("sequential (1 stream): %.2f ms\n", seq);
printf("streamed (4 streams): %.2f ms\n", str);
printf("speedup: %.2fx\n", seq / str);
printf("last value: %.1f\n", h[N - 1]);
cudaFreeHost(h); cudaFree(d);
return 0;
}sequential (1 stream): 8.94 ms streamed (4 streams): 5.12 ms speedup: 1.75x last value: 2.0
The numbers depend on the GPU and the link. On a fast NVLink system the copies are cheaper and the speedup is smaller; on PCIe it can approach 2–3×. What matters is the shape:
The copy engine and the compute units are different hardware. A single stream can only be doing one of them at a time; multiple streams let the GPU use both.
Events: markers and timers#
An event is a marker you enqueue into a stream. It records a timestamp when it reaches the front of the queue.
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start, stream);
kernel<<<grid, block, 0, stream>>>(...);
cudaEventRecord(stop, stream);
cudaEventSynchronize(stop);
float ms = 0.0f;
cudaEventElapsedTime(&ms, start, stop);
printf("%.3f ms\n", ms);Events are also dependencies. cudaStreamWaitEvent(otherStream, event) makes one stream wait until another reaches a point — without blocking the host. This is how you build a graph of work by hand.
cudaEventRecord(done, streamA);
cudaStreamWaitEvent(streamB, done, 0); // streamB waits for streamAcudaEventSynchronize waits for the host. cudaEventQuery polls. Destroy events with cudaEventDestroy.
Synchronisation choices#
| Call | Waits for |
|---|---|
cudaDeviceSynchronize() | Everything on the device |
cudaStreamSynchronize(s) | All work in stream s |
cudaStreamQuery(s) | Non-blocking; returns cudaErrorNotReady or cudaSuccess |
cudaEventSynchronize(e) | The event (and everything before it in its stream) |
cudaStreamWaitEvent(s, e) | Makes s wait, without blocking the host |
cudaLaunchHostFunc(s, fn, arg) | Calls a host function after prior work in s |
Prefer the narrowest wait that is correct. A cudaDeviceSynchronize() in an inner loop serialises everything and throws away the benefit of streams.
Priorities and non-blocking streams#
int least, greatest;
cudaDeviceGetStreamPriorityRange(&least, &greatest); // low, high
cudaStreamCreateWithPriority(&stream, cudaStreamNonBlocking, greatest);Priority is a hint to the scheduler, not a guarantee. It helps when a latency-sensitive stream competes with a long-running background kernel.
cudaStreamNonBlocking opts a stream out of legacy default-stream synchronisation. It is usually what you want for library code that must not serialise against an application's default stream.
When streams stop helping#
- A single kernel already fills the GPU. Streams cannot make it wider.
- Every operation depends on the previous one. There is nothing to overlap.
- Copies are pageable. They serialise no matter which stream they are in.
- You synchronise after every launch. You have rebuilt a sequential program with extra API calls.
Streams are about independent work. If your chunks are not independent, fix the algorithm first.
Beyond streams: graphs#
A sequence of launches and copies can be captured into a CUDA graph and replayed with one API call. Graphs remove per-launch CPU overhead and preserve the dependency structure:
cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal);
// ... enqueue the same launches and copies ...
cudaGraph_t graph;
cudaStreamEndCapture(stream, &graph);
cudaGraphExec_t exec;
cudaGraphInstantiate(&exec, graph, 0);
cudaGraphLaunch(exec, stream);This matters when a kernel takes microseconds but launching it takes longer than running it — small inference steps, iterative solvers, and loops of tiny kernels.
Exercises#
- Change
cudaMallocHosttomallocin the overlap program. How do the times change? Why? - Add a fifth stream. Does the speedup improve, stay flat, or get worse? Why?
- Time the kernel alone with events. What fraction of the sequential time is copy?
- Use
cudaStreamWaitEventto make stream 1 wait for stream 0 halfway through. Verify the ordering withprintftimestamps on the host. - Capture the four-stream version into a CUDA graph and compare launch overhead for 1,000 iterations.
Next: the performance chapter, where all of these pieces — coalescing, occupancy, and overlap — become a checklist.