在内核中使用 printf
查看设备线程产生的输出
在内核中使用 printf 是 CoddyKit 上的免费 CUDA Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 CUDA Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 CUDA Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Printing from the GPU
Believe it or not, you can call printf right inside a kernel. It is the simplest way to peek at what your threads are doing. 👀
__global__ void hi() {
printf("Hello from the GPU\n");
}Every Thread Prints
Remember the kernel runs in every thread, so a single printf line fires once per thread. Launch 256 threads and you get 256 lines.
hi<<<1, 256>>>(); // 256 hellosIdentify Each Thread
Include the threadIdx in your message so you can tell threads apart. Otherwise the output is just a wall of identical lines.
printf("thread %d\n", threadIdx.x);Output Order Is Not Fixed
Threads run in parallel, so the printed order is unpredictable. Do not rely on lines arriving in index sequence.
Format Strings Work
Device printf supports the usual format specifiers like %d, %f, and %s. It feels just like host printf.
printf("i=%d val=%f\n", i, x[i]);Output Goes to a Buffer
Device output is staged in a GPU buffer and flushed to your console later, not the instant printf runs. That is normal.
You Must Wait to See It
Because the launch is async, you will not see prints until the GPU finishes. Call cudaDeviceSynchronize to flush them.
hi<<<1, 4>>>();
cudaDeviceSynchronize();Guard Heavy Printing
Printing from millions of threads floods the buffer. Guard it so only thread 0 prints, or only a few do.
if (threadIdx.x == 0) printf("block done\n");Great for Quick Debugging
printf is your fastest debugging tool: drop one in to check an index or a value, confirm the bug, then remove it.
printf("i=%d should be < n=%d\n", i, n);It Slows Kernels Down
Heavy printing hurts performance badly. Use it to find a problem, then delete it before you measure real speed.
Old GPUs May Differ
Device printf needs a reasonably modern compute capability (2.0 and up). Almost every current GPU supports it just fine.
Quick Check
Check what you know about device printf.
Recap: Kernel printf
Use printf to peek inside threads, add threadIdx to tell them apart, sync to flush, and remove it before timing. Handy tool! 🎉
常见问题解答
「在内核中使用 printf」课时是免费的吗?
是的 — 「在内核中使用 printf」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 CUDA Academy 课程的其余内容,请升级到 CoddyKit PRO。 CUDA Academy 课程共包含 4 节课。
「在内核中使用 printf」这节课中我会学到什么?
查看设备线程产生的输出 你通过在浏览器中直接运行的动手代码来练习 CUDA Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 CUDA Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 CUDA Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「在内核中使用 printf」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 CUDA Academy 课中编写并运行代码吗?
能。每节 CUDA Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 内核的组成
- 三重尖括号启动语法
- 在内核中使用 printf
- 详解 cudaDeviceSynchronize