当您在设备内部调用cudaMalloc时,实际会发生什么

Whats actually happens when you call cudaMalloc inside device?

本文关键字:什么 cudaMalloc 调用 内部      更新时间:2023-10-16

这实际上是有效的,所以我想知道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);
}

从计算能力3.5开始,您可以在内核中使用部分cuda运行时api。这些方法在文档中被声明为__host__ __device__,就像这里一样:

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

在设备上分配内存。

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

还有另一种在设备上动态分配内存的方法:使用malloc,这是以不同的方式实现的(本文对此进行了说明)。它使用的是一个小内存堆,不需要相同的计算能力。