【发布时间】:2014-09-12 14:46:16
【问题描述】:
我有返回 C++ 主机端数组的 cuda/C++ 代码。我想在 MATLAB 中操作这些数组,所以我以 mex 格式重写了我的代码并用 mex 编译。
我通过将预先分配的数组从 MATLAB 传递到 mex 脚本来使其工作,但这极大地减慢了速度。 (54 秒 vs 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 秒使用 mex,14 秒使用 c++/cuda)
【问题讨论】:
-
您指的是哪个 MathWorks 示例?
-
标准 cuda mex 示例“timestwo”mathworks.com/help/distcomp/…
-
该示例采用
gpuArray输入并返回gpuArray output。您想将常规数组输入/输出,对吗? -
查看我的更新答案。另外,在使用
mxCreateNumericMatrix时删除delete h_F0;。 -
我看到的确实没什么可清理的。确保不要计时第一次运行。
标签: c++ matlab dynamic cuda mex