我有返回C++主机端数组的cuda/C++代码。我想在MATLAB中操作这些数组,所以我用mex格式重写了代码,并用mex编译了代码。
我通过将预先分配的数组从MATLAB传递到mex脚本来工作,但这极大地减缓了速度。(54秒对14秒无梅克斯)
下面是简化的、没有输入1输出版本的代码的慢速解决方案:
#include "mex.h"
#include "gpu/mxGPUArray.h"
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include "cuda.h"
#include "curand.h"
#include <cuda_runtime.h>
#include "math.h"
#include <curand_kernel.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#define iterations 159744
#define transMatrixSize 2592 // Just for clarity. Do not change. No need to adjust this value for this simulation.
#define reps 1024 // Is equal to blocksize. Do not change without proper source code adjustments.
#define integralStep 13125 // Number of time steps to be averaged at the tail of the Force-Time curves to get Steady State Force
__global__ void kern(float *masterForces, ...)
{
int globalIdx = ((blockIdx.x + (blockIdx.y * gridDim.x)) * (blockDim.x * blockDim.y)) + (threadIdx.x + (threadIdx.y * blockDim.x));
...
...
{
...
{
masterForces[i] = buffer[0]/24576.0;
}
}
}
...
}
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, mxArray const *prhs[])
{
...
plhs[0] = mxCreateNumericMatrix(iterations,1,mxSINGLE_CLASS,mxREAL);
float *h_F0 = (float*) mxGetData(plhs[0]);
//Device input vectors
float *d_F0;
..
// Allocate memory for each vector on GPU
cudaMalloc((void**)&d_F0, iterations * sizeof(float));
...
//////////////////////////////////////////////LAUNCH ////////////////////////////////////////////////////////////////////////////////////
kern<<<1, 1024>>>( d_F0);
//////////////////////////////////////////////RETRIEVE DATA ////////////////////////////////////////////////////////////////////////////////////
cudaMemcpyAsync( h_F0 , d_F0 , iterations * sizeof(float), cudaMemcpyDeviceToHost);
///////////////////Free Memory///////////////////
cudaDeviceReset();
////////////////////////////////////////////////////
}为什么这么慢?
编辑: Mex是用较旧的体系结构(SM_13)而不是SM_35编译的。现在是时候了。(16 s与mex,14 s与c++/cuda )
发布于 2014-07-22 00:18:36
如果您的数据自动化系统代码的输出是普通的老数据主机端(相对于设备端)数组,则不需要使用mxGPUArray,就像用new创建的float的Forces1数组一样。您所引用的MathWorks示例可能演示了如何使用MATLAB的gpuArray和内置的CUDA功能,而不是如何在MEX函数中传递数据和从常规的CUDA函数中传递数据。
如果您可以在CUDA函数之外和之前初始化Forces1 (或完整代码中的h_F0 )(例如在mexFunction中),那么解决方案只是从new更改为mxCreate*函数之一(即mxCreateNumericArray、mxCreateDoubleMatrix、mxCreateNumericMatrix等),然后将数据指针传递到您的mxCreate*函数:
plhs[0] = mxCreateNumericMatrix(iterations,1,mxSINGLE_CLASS,mxREAL);
float *h_F0 = (float*) mxGetData(plhs[0]);
// myCudaWrapper(...,h_F0 ,...) /* i.e. cudaMemcpyAsync(h_F0,d_F0,...)因此,对代码的唯一更改是:
取代
float *h_F0 = new float[(iterations)];使用
plhs[0] = mxCreateNumericMatrix(iterations,1,mxSINGLE_CLASS,mxREAL);
float *h_F0 = (float*) mxGetData(plhs[0]);删除
delete h_F0;注意:如果您的CUDA代码拥有输出主机端数组,则必须将数据复制到mxArray中。这是因为除非您将mexFunction输出分配给mx API,否则您分配的任何数据缓冲区(例如使用mxSetData)都不会由memory管理器处理,并且您将有一个分段错误,或者最多是内存泄漏。
https://stackoverflow.com/questions/24876229
复制相似问题