我在mexFunction
中有一个for
循环,该循环在每次迭代时都会显示一些信息。考虑此简单的代码,该代码将在MATLAB命令窗口中打印100行,并在每次迭代中进行更新:
#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int numiters = 100;
/* initialize random seed: */
srand(time(NULL));
for (int iter = 1; iter <= numiters; ++iter)
{
int rand_num = rand() % 100 + 1;
/* Print info in matlab */
std::ostringstream buffer;
buffer << "iter = " << iter << " of " << numiters <<
". random number = " << rand_num << endl;
/* need something similar to clc here */
mexPrintf("%s", buffer.str().c_str());
}
return;
}
在调用mexPrintf()
之前,我希望在每次迭代中清除Matlab的命令窗口。
我知道我可以使用mexCallMATLAB
调用MATLAB的clc
,但是我不确定在每次迭代时调用MATLAB是否非常有效,因此我需要C 的本机。
我对mexCallMATLAB
效率低下的假设是错误的,这要归功于@ander Biguri的头部。我使用以下测试代码与mexCallMATLAB
进行比较。
TL; DR -Timing结果
- 使用
mexCallMATLAB(0, NULL, 0, NULL, "clc");
:mean time per iteration = 0.1016885 sec
- 没有
mexCallMATLAB(0, NULL, 0, NULL, "clc");
:mean time per iteration = 0.0978730 sec
详细信息
测试台摘要
- 创建一个带有100万个随机整数的向量,并拿出平均值。
- 重复500次迭代。
- 计算每次迭代所需的时间并保存在向量中。
- 平均迭代时间获得平均每次迭代的时间。
代码
#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <ctime>
#include <vector>
using namespace std;
extern bool ioFlush(void);
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
int numiters = 500;
/* initialize random seed: */
srand(time(NULL));
std::vector<double> all_times(numiters);
for (int iter = 1; iter <= numiters; ++iter)
{
/* tic */
clock_t begin = clock();
std::vector<int> rand_vec;
for(std::size_t i = 0; i < 1000000; ++i)
rand_vec.push_back( rand() % 100 + 1 );
double vec_mean = 0.0;
for(std::size_t i = 0; i < rand_vec.size(); ++i)
vec_mean += rand_vec[i];
vec_mean /= rand_vec.size();
/* clear screen */
mexCallMATLAB(0, NULL, 0, NULL, "clc");
/* toc */
double time_elapsed = double(clock() - begin) / CLOCKS_PER_SEC;
/* Print data in matlab */
std::ostringstream buffer;
buffer << "iter " << iter << " of " << numiters <<
". random vector mean = " << vec_mean <<
". in " << time_elapsed << "s" << endl;
mexPrintf("%s", buffer.str().c_str());
ioFlush();
all_times[iter] = time_elapsed;
}
double avg_time = 0.0;
for(std::size_t i = 0; i < all_times.size(); ++i)
avg_time += all_times[i];
avg_time /= all_times.size();
mexPrintf("navg time per iter = %3.7fn", avg_time);
return;
}
请注意,在每次迭代时都需要更新命令窗口所需的无证件功能ioFlush()
。在此处查看有关它的更多详细信息。
编译
- 在Windows上使用Visual Studio:在源文件中添加
#pragma comment(lib, "libmwservices.lib")
。 - 在Ubuntu上使用GCC:使用
mex yourFile.cpp -lmwservices
编译