cuda内存分配函数
提示:以下是本篇文章正文内容,下面内容可供参考
一、cuda函数列表
1. cudaMalloc
int main(){
int a = 0, *a_d;
cudaMalloc((void**) &a_d, sizeof(int));
cudaMemcpy(a_d, &a, sizeof(int), cudaMemcpyHostToDevice);
kernel<<<1, 1>>>(a_d);
cudaMemcpy(&a, a_d, sizeof(int), cudaMemcpyDeviceToHost);
printf("a = %d\n", a);
cudaFree(a_d);
}
2.cudaMallocPitch
#include <iostream>
#include <cuda_runtime.h>
using namespace std;
int main()
{
float * pDeviceData = NULL;
int width = 10 * sizeof(float);
int height = 10 * sizeof(float);
size_t pitch;
cudaError err = cudaSuccess;
err = cudaMallocPitch(&pDeviceData, &pitch, width, height);
if (err != cudaSuccess)
{
cout << "call cudaMallocPitch fail!!!" << endl;
exit(1);
}
cout << "width: " << width << endl;
cout << "height: " << height << endl;
cout << "pitch: " << pitch << endl;
cudaFree(pDeviceData);
return 0;
}
3.cudaMalloc3D
int main()
{
cudaError err = cudaSuccess;
cudaPitchedPtr pitchPtr;
cudaExtent extent;
extent.width = 10 * sizeof(float);
extent.height = 22 * sizeof(float);
extent.depth = 33 * sizeof(float);
err = cudaMalloc3D(&pitchPtr,extent);
if (err != cudaSuccess)
{
cout << "call cudaMalloc3D fail!!!" << endl;
exit(1);
}
cout << "width: " << extent.width << endl;
cout << "height: " << extent.height << endl;
cout << "depth: " << extent.depth << endl;
cout << endl;
cout << "pitch: " << pitchPtr.pitch << endl;
cout << "xsize: " << pitchPtr.xsize << endl;
cout << "ysize: " << pitchPtr.ysize << endl;
cudaFree(pitchPtr.ptr);
return 0;
}
总结
内存分配函数有cudaMalloc、cudaMallocPitch、cudaMalloc3D分别分配一维、二维、三位内存空间。
本文介绍了CUDA中的三种内存分配函数:cudaMalloc用于一维内存分配,cudaMallocPitch针对二维内存进行优化,而cudaMalloc3D则支持三维内存空间的分配。这些函数在GPU编程中扮演关键角色。
293

被折叠的 条评论
为什么被折叠?



