array_atan2.cuh 1.61 KB
#ifndef STIM_CUDA_ARRAY_ATAN2_H
#define STIM_CUDA_ARRAY_ATAN2_H

#include <iostream>
#include <cuda.h>
#include <cmath>
#include <stim/cuda/cudatools.h>

namespace stim{
	namespace cuda{

		template<typename T>
		__global__ void cuda_atan2(T* y, T* x, T* r, unsigned int N){

			//calculate the 1D index for this thread
			int idx = blockIdx.x * blockDim.x + threadIdx.x;

			if(idx < N){
				r[idx] = atan2(y[idx], x[idx]);
			}

		}

		template<typename T>
		void gpu_atan2(T* y, T* x, T* r, unsigned int N){

			//get the maximum number of threads per block for the CUDA device
			int threads = stim::maxThreadsPerBlock();

			//calculate the number of blocks
			int blocks = N / threads + 1;

			//call the kernel to do the multiplication
			cuda_atan2 <<< blocks, threads >>>(y, x, r, N);

		}

		template<typename T>
		void cpu_atan2(T* y, T* x, T* cpu_r, unsigned int N){

			//allocate memory on the GPU for the array
			T* gpu_x; 
			T* gpu_y; 
			T* gpu_r;
			HANDLE_ERROR( cudaMalloc( &gpu_x, N * sizeof(T) ) );
			HANDLE_ERROR( cudaMalloc( &gpu_y, N * sizeof(T) ) );
			HANDLE_ERROR( cudaMalloc( &gpu_r, N * sizeof(T) ) );

			//copy the array to the GPU
			HANDLE_ERROR( cudaMemcpy( gpu_x, x, N * sizeof(T), cudaMemcpyHostToDevice) );
			HANDLE_ERROR( cudaMemcpy( gpu_y, y, N * sizeof(T), cudaMemcpyHostToDevice) );

			//call the GPU version of this function
			gpu_atan2<T>(gpu_y, gpu_x ,gpu_r, N);

			//copy the array back to the CPU
			HANDLE_ERROR( cudaMemcpy( cpu_r, gpu_r, N * sizeof(T), cudaMemcpyDeviceToHost) );

			//free allocated memory
			cudaFree(gpu_x);
			cudaFree(gpu_y);
			cudaFree(gpu_r);

		}
		
	}
}



#endif