相同的代码,mex是慢得多和纯C,为什么?

时间:2013-08-10 00:00:18

标签: cuda mex

我有一个用于Matlab的CUDA程序,但是mex版本比Visual Studio版本要慢得多,尽管代码是相同的,除了简单的mexFunction for in / out参数。 mex版需要3秒,而纯C需要0.5秒。

我正在使用Quadro K2000M卡,CUDA功能3.0,CUDA驱动程序5.5,运行时5.0,使用Visual Studio 2010编程。我按照MATLAB的mexGPUExample.cu步骤,仅将设置更改为-gencode = arch = compute_30 ,代码= \" sm_30,compute_30 \" (删除较低版本的标志)。

详情,

纯C代码(在Nsight 3.1中为Visual Sutdio 2010项目创建,将代码生成更改为compute_30,sm_30)

int main(int argc, char *argv[]){
clock_t begin, end;
double elapsed_time;

// some codes that prepare parameters from argc and argv

begin = clock();
a_function_that_calls_a_cuda_kernel(parameters);
end = clock();
elapsed_time = (double)(end - begin) / CLOCKS_PER_SEC;
printf("elapsed time: %f seconds\n", elapsed_time);

return 0;
}

Matlab mex代码(按照MATLAB的mexGPUExample.cu,http://www.mathworks.se/help/distcomp/create-and-run-mex-files-containing-cuda-code.html中的详细信息,稍微修改设置为-gencode = arch = compute_30,code = \" sm_30,compute_30 \" )

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
clock_t begin, end;
double elapsed_time;

// some codes that prepare parameters from prhs

begin = clock();
a_function_that_calls_a_cuda_kernel(parameters);
end = clock();
elapsed_time = (double)(end - begin) / CLOCKS_PER_SEC;
mexPrintf("elapsed time: %f seconds\n", elapsed_time);      
}

mex版需要3秒,而纯C需要0.5秒,为什么?非常感谢任何提示。

1 个答案:

答案 0 :(得分:1)

你的问题不清楚。我假设以下比较条款:

  

您有一个CUDA代码,当在Visual Studio下编译为独立程序时,比mexFunction接口并编译为在Matlab下调用时更快。

你应该知道,第一次调用mexFunction是“慢”,因为CUDA上下文已经设置,内核由驱动程序处理,代码上传到GPU。

因此,为了对执行时间进行有意义的估计,首先应该通过调用一次来“预热”内核,然后对后续调用的执行进行计时。如果代码很快,时间应该计算为许多呼叫的平均时间。