cuda编程入门示例5

#include 
#include 
#include 
#include 

#define BLOCK_SIZE 16
static void HandleError(cudaError_t err, const char *file, int line)
{
	if (err != cudaSuccess)
	{
		printf("%s in %s at line %d\n", cudaGetErrorString(err), file, line);
		exit(EXIT_FAILURE);
	}
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))

#define HANDLE_NULL( a ) {if ((a) == NULL) { \
	printf("Host memory failed in %s at line %d\n", \
	__FILE__, __LINE__); \
	exit(EXIT_FAILURE); }}

static void GenerateNumbers(int *number, int size)
{
	for (int i = 0; i < size; i++)
	{
		number[i] = rand() % 10;
	}
}

static bool InitCUDA()
{
	int count;

	cudaGetDeviceCount(&count);
	if (count == 0)
	{
		fprintf(stderr, "There is no device.\n");
		return false;
	}

	int i;
	for (i = 0; i < count; i++)
	{
		cudaDeviceProp prop;
		if (cudaGetDeviceProperties(&prop, i) == cudaSuccess)
		{
			if (prop.major >= 1)
			{
				break;
			}
		}
	}

	if (i >= count)
	{
		fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
		return false;
	}

	cudaSetDevice(i);

	return true;
}

//1个block,block内256个thread,threadIdx.x = 0的线程计时,每个线程计算一个结果
__global__ static void sumOfSquares(int *num, int size, int* result, clock_t* time)
{
	int sum = 0;
	clock_t start;
	const int tid = threadIdx.x;
	const int gap = (size + blockDim.x - 1) / blockDim.x;

	if (tid == 0)
	{
		start = clock();
	}

	for (int index = tid * gap; index < (tid + 1) * gap; index++)
	{
		if (index < size)
		{
			sum += num[index] * num[index];
		}
	}

	result[tid] = sum;

	if (tid == 0)
	{
		*time = clock() - start;
	}
}

int main(int argc, char *argv[])
{
	if (!InitCUDA())
	{
		return -1;
	}
	printf("CUDA initialized.\n");

	const int  thread_num = 256;
	const int DATA_SIZE = 1024;
	int data[DATA_SIZE];
	GenerateNumbers(data, DATA_SIZE);

	int* gpudata, *result, gpuResult[thread_num];
	clock_t* devTime, gpuTime, cpuTime;
	HANDLE_ERROR(cudaMalloc((void **)&gpudata, sizeof(int)* DATA_SIZE));
	HANDLE_ERROR(cudaMalloc((void**)&result, sizeof(int)* thread_num));
	HANDLE_ERROR(cudaMalloc((void**)&devTime, sizeof(clock_t)));
	HANDLE_ERROR(cudaMemcpy(gpudata, data, sizeof(int)* DATA_SIZE, cudaMemcpyHostToDevice));

	sumOfSquares << <1, thread_num, 0 >> >(gpudata, DATA_SIZE, result, devTime);

	HANDLE_ERROR(cudaMemcpy(gpuResult, result, sizeof(int)* thread_num, cudaMemcpyDeviceToHost));
	HANDLE_ERROR(cudaMemcpy(&gpuTime, devTime, sizeof(clock_t), cudaMemcpyDeviceToHost));

	int sum = 0;
	for (int i = 0; i < thread_num; i++)
	{
		sum += gpuResult[i];
	}

	cudaFree(gpudata);
	cudaFree(result);
	cudaFree(devTime);

	printf("sum (GPU): %d, time: %d\n", sum, gpuTime);

	int sumCPU = 0;
	cpuTime = clock();
	for (int i = 0; i < DATA_SIZE; i++)
	{
		sumCPU += data[i] * data[i];
	}
	cpuTime = clock() - cpuTime;
	printf("sum (CPU): %d, time:%d\n", sumCPU, cpuTime);
	printf("Result %s\n", sum == sumCPU ? "OK" : "Wrong");

	//remember to release the device
	cudaDeviceReset();

	return 0;
}

你可能感兴趣的:(cuda编程常用代码示例,c/c++)