Tuesday, June 29, 2010

First CUDA Quine

As you may know, a quine is a short program that prints its own source code using common facilities of the language. With CUDA 3.0 and Fermi's support of printf(), this isn't very difficult to do with CUDA. Here is an example, the first I've seen to run on a GPU.


$ cat quine.cu
#include <stdio.h>
__device__ const char *f="#include <stdio.h>%c__device__ const char *f=%c%s%c; __global__ void k(){ printf(f,10,34,f,34,10); } int main() { k<<< dim3(1,1),dim3(1,1)>>>(); cudaThreadExit(); return 0; }%c"; __global__ void k(){ printf(f,10,34,f,34,10); } int main() { k<<< dim3(1,1),dim3(1,1)>>>(); cudaThreadExit(); return 0; }

$ nvcc --run quine.cu -arch sm_20 > quine2.cu
$ diff quine.cu quine2.cu
$ nvcc --run quine2.cu -arch sm_20 > quine3.cu
$ diff quine.cu quine3.cu
$