Thread: CUDA Tutorial
View Single Post
Old 10-18-11, 12:50 AM   #3
ViN86
 
Join Date: Mar 2004
Posts: 15,486
Default Re: CUDA Guide/Tutorials

Intro and "Hello world" application

If you're new to CUDA (like I am) you should definitely check out some books. A good starter is CUDA by Example. It goes through the basics and is a good introduction. They also provide sample code from the book and it is easy to follow. You can obtain that from here. I recommend you check out the samples as they are a good introduction. I will however use my own examples and will try to attach them to the posts so you can download/compile them. Without further ado, let's begin.

Regular C code and CUDA code work together seamlessly. You can use nvcc to compile regular C programs. For example, let's take regular C code and compile with nvcc.

Code:
#include <stdio.h>

int main(){
	
	// Say hello to the world
	printf("Hello, world!\n");
	
	return 0;

}
Compiling via nvcc helloworld.c should produce a program labeled a.exe. If you run this program, you are greeted with the following.

Code:
Hello, world!
Now we can see that the CUDA compiler recognizes regular C code as it should. Now let's look at a piece of code which actually uses the GPU, although we won't do anything just yet.

Code:
#include <stdio.h>

__global__ void gpuhw( void ){
	// Do nothing on the GPU... for now
}

int main(){
	
	// Call GPU function gpuhw, which does nothing
	gpuhw<<<1,1>>>();
	
	// Call our printf statement
	printf("Hello, world!\n");
	return 0;

}
Here we see a few new things which we need to take note of. First, we include a new function above with the prefix __global__. This tells our compiler that this code can be called to run on the device (your GPU) from the host. Later we will see __device__ which notifies the compiler of functions that can be called by the GPU. Also, we see a call to this function gpuhw with some funny brackets after this. These numbers specify the number of blocks and threads, respectively, for the card to use. We will discuss later what this means.

Compiling the helloworldgpu.cu file and running the executable, should output the same thing.

Code:
Hello, world!
Congrats, you just ran your first CUDA code. That concludes this basic introduction. I recommend using .cu extensions for your CUDA code so you can keep them organized and separate from your C code, but obviously it's up to your preference.

In the future we will learn more about how to handle blocks and threads per block on the GPU. Stay tuned.
Attached Files
File Type: zip Lesson1.zip (515 Bytes, 88 views)
ViN86 is offline