array_cos.cuh 1.44 KB

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

namespace stim{
	namespace cuda{

		template<typename T>
		__global__ void cuda_cos(T* ptr1, T* out, unsigned int N){

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

			if(idx < N){
				out[idx] = cos(ptr1[idx]);


		template<typename T>
		void gpu_cos(T* ptr1, T* out, 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_cos <<< blocks, threads >>>(ptr1, out, N);


		template<typename T>
		void cpu_cos(T* ptr1, T* cpu_out, unsigned int N){

			//allocate memory on the GPU for the array
			T* gpu_ptr1; 
			T* gpu_out;
			HANDLE_ERROR( cudaMalloc( &gpu_ptr1, N * sizeof(T) ) );
			HANDLE_ERROR( cudaMalloc( &gpu_out, N * sizeof(T) ) );

			//copy the array to the GPU
			HANDLE_ERROR( cudaMemcpy( gpu_ptr1, ptr1, N * sizeof(T), cudaMemcpyHostToDevice) );

			//call the GPU version of this function
			gpu_cos<T>(gpu_ptr1 ,gpu_out, N);

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

			//free allocated memory