当你在设备中调用cudaMalloc时,实际上会发生什么?

时间:2016-05-23 05:44:25

标签: c++ cuda gpgpu

这实际上有效,所以我想知道cuda是否在线程中的设备上动态分配内存?如果是这样的话__device__ malloc的用途是什么,因为相比之下要快得多?当我在内核中使用cudaMalloc时,我问的是幕后真的发生了什么,因为它似乎比堆上的设备malloc快得多。

#include <iostream>
#include <numeric>
#include <stdlib.h>

__global__ void testMem(int* time){
    int* a;
    cudaMalloc(&a,sizeof(int));
    a[0] = 4;
    time = a[0];
}

__global__ void testMem2(int* time){

}
int main(){
    int* h_time = (int*)malloc(sizeof(int));
    h_time[0] =0;
    int* d_time;
    cudaMalloc(&d_time,sizeof(int));
    clock_t start1 = clock();
    cudaMemcpy(d_time,h_time,sizeof(int),cudaMemcpyHostToDevice);

    testMem<<<1,1>>>(d_time);
    cudaMemcpy(h_time,d_time,sizeof(int),cudaMemcpyDeviceToHost);
    cudaDeviceSynchronize();
    clock_t end1 = clock();

    int result = end1- start1;
    //float result = (float)*h_time;
    //result =result/ CLOCKS_PER_SEC;
    std::cout<<result<<std::endl;
    std::cout<<*h_time<<std::endl;
    //std::cout<<(1<<10);
    cudaFree(d_time);
    free(h_time);

}

1 个答案:

答案 0 :(得分:1)

启动计算能力3.5,您可以在内核中使用cuda运行时api的一部分。这些方法在文档中声明为__host__ __device__,就像here

一样
  

__host__ ​ __device__ ​cudaError_t cudaMalloc ( void** devPtr, size_t size )

     

在设备上分配内存。

执行此操作时,请提醒链接设备运行时库:cudadevrt.lib

还有另一种在设备上动态分配内存的方法:malloc的使用,实现方式不同(记录为here)。它使用的是小内存堆,并且不需要相同的计算能力。