我在for
中有一个mexFunction
循环,它会在每次迭代时显示一些信息。考虑这个简单的代码,它将在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 ++。
答案 0 :(得分:1)
我对mexCallMATLAB
效率低下的假设是错误的,感谢@Ander Biguri的提升。我使用以下测试代码来比较有和没有mexCallMATLAB
的时间。
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
#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.7f\n", avg_time);
return;
}
请注意ioFlush()
的使用,#pragma comment(lib, "libmwservices.lib")
是在每次迭代时更新命令窗口所需的未记录的函数。查看有关它的更多详细信息here。
mex yourFile.cpp -lmwservices
。date('d-M-Y')