使用cudaMalloc分配一个矩阵 [英] Using cudaMalloc to allocate a matrix
问题描述
我使用cudaMalloc和cudaMemcpy分配一个矩阵并将其复制到向量数组中,如下所示:
I am using cudaMalloc and cudaMemcpy to allocate a matrix and copy into it arrays of vectors , like this:
float **pa;
cudaMalloc((void***)&pa, N*sizeof(float*)); //this seems to be ok
for(i=0; i<N; i++) {
cudaMalloc((void**) &(pa[i]), N*sizeof(float)); //this gives seg fault
cudaMemcpy (pa[i], A[i], N*sizeof(float), cudaMemcpyHostToDevice); // also i am not sure about this
}
我的指示有什么问题?
提前感谢
What is wrong with my instructions? Thanks in advance
P.S。 A [i]是一个向量
P.S. A[i] is a vector
现在我想将矩阵从设备复制到矩阵host:
Now i'm trying to copy a matrix from the Device to a matrix from the host:
假设我在设备中有** pc,而且pgpu在主机中:
Supposing I have **pc in the device, and **pgpu is in the host:
cudaMemcpy (pgpu, pc, N*sizeof(float*), cudaMemcpyDeviceToHost);
for (i=0; i<N; i++)
cudaMemcpy(pgpu[i], pc[i], N*sizeof(float), cudaMemcpyDeviceToHost);
=错误....
推荐答案
pa
在设备内存中,因此&(pa [i])
不做你所期望的。这将工作
pa
is in device memory, so &(pa[i])
does not do what you are expecting it will. This will work
float **pa;
float **pah = (float **)malloc(pah, N * sizeof(float *));
cudaMalloc((void***)&pa, N*sizeof(float*));
for(i=0; i<N; i++) {
cudaMalloc((void**) &(pah[i]), N*sizeof(float));
cudaMemcpy (pah[i], A[i], N*sizeof(float), cudaMemcpyHostToDevice);
}
cudaMemcpy (pa, pah, N*sizeof(float *), cudaMemcpyHostToDevice);
在主机内存中构建指针数组,然后将其复制到设备。 <$>我不知道你希望从 A
中读取,但我怀疑内部 cudaMemcpy
可能
ie. build the array of pointers in host memory and then copy it to the device. I am not sure what you are hoping to read from A
, but I suspect that the inner cudaMemcpy
probably isn't doing what you want as written.
从性能的角度来看,指针数组在GPU上不是一个好主意。
Be forewarned that from a performance point of view, arrays of pointers are not a good idea on the GPU.
这篇关于使用cudaMalloc分配一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!