简体   繁体   English

我如何克服CUDA中的内存分配

[英]how can i overcome memory allocation in cuda

I have a question. 我有个问题。 I'm working with the 4.0 cuda. 我正在使用4.0 cuda。 I have the following code: 我有以下代码:

in my cudaHeader.h: 在我的cudaHeader.h中:

#include <stdlib.h>

extern "C" void wrapperfunction(int* array);

in my cudaCpp.cpp: 在我的cudaCpp.cpp中:

#include <stdio.h>
......
int main()
{
  int array[50] = {0, 1, 2, ..........,49};
  ...........

  while(true)
  {
   ........

   wrapperfunction(array);

   ........

   }
  return 0;

}

in my cuda.CU: 在我的cuda.CU中:

__global__ void kernel(int *new_arrayG, int *arrayG,int *const_arrayG)
{
  int x = threadIdx.x;

  new_arrayG[x] = arrayG[x] + const_arrayG[x];
  __syncthreads();
}

extern "C" int wrapperfunction(int* array)
{

  static int const_array[50] = {0, 1, 2, ........., 49};  //any constant data
  int *arrayG, *new_arrayG, *const_arrayG;
  int size = 50 * sizeof(int);

  cudaMalloc((void**)&arrayG, size);
  cudaMalloc((void**)&new_arrayG, size);
  cudaMalloc((void**)&const_arrayG, size);

  cudaMemcpy(const_arrayG, const_array, size, cudaMemcpyHostToDevice);
  cudaMemcpy(arrayG, array, size, cudaMemcpyHostToDevice);

  Kernel<<<1, 50>>>(new_arrayG, arrayG, const_arrayG);

  cudaMemcpy(array, new_arrayG, size, cudaMemcpyDeviceToHost);

  cudaFree(arrayG);cudaFree(new_arrayG);cudaFree(const_arrayG);
}

this a sample from my code, i wanna to say each time i call the wrapperfunction from my .cpp code the program allocate the static array and free it at the end and it it takes much time and at real i deal with very large static array and each time call this function i take very much time. 这是我代码中的一个示例,我想说的是,每次我从.cpp代码中调用wrapper函数时,程序都会分配静态数组并在最后释放它,这需要很多时间,实际上我要处理非常大的静态数组每次调用此函数我都会花费很多时间。 so i wanna to a way to allocate my static arrays one time at the begining of the program and free them at the end of my program(application). 所以我想一种在程序开始时一次分配我的静态数组,并在我的程序(应用程序)结束时释放它们的方法。 Plz. l any helping. 任何帮助。

Thanks. 谢谢。

Simply allocate your arrays once for all in your main(), moving it to some .cu file. 只需在main()中一次为所有数组分配数组,然后将其移至某个.cu文件即可。 And them, pass their addresses to the wrapping function. 然后,将其地址传递给包装函数。

Also, you should check the return of such calls. 另外,您应检查此类呼叫的返回。

Furthermore, try not to use any C header in your C++ program if you have C++ header equivalent. 此外,如果具有等效的C ++头,请尝试在C ++程序中不要使用任何C头。 Use #include <cstdio> instead of #include <cstdlib> . 使用#include <cstdio>而不是#include <cstdlib>

Finally, as you're only dealing with cpp code, you should drop your extern "C". 最后,由于您只处理cpp代码,因此应删除extern“ C”。

Or if you do want work with C code out of CUDA code, quit using .cpp file extension. 或者,如果您确实想使用CUDA代码之外的C代码,请使用.cpp文件扩展名退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM