Introduction
To any Matlab user interested in performance, the lack of a precision timer with microsecond resolution is a major shortcoming. Under Linux there are kernel patches available which provide this functionality, however under Windows one has to make to with millisecond resolution. Thankfully Keith Wansbrough has put his TSCtime package into the public domain providing precision timing from C/C++ programs under Visual C++.
Mex Wrapper Implementation
This project consists of a Mex wrapper function to access Keith Wansbrough's TSCtime high-precision time measurement functions from within Matlab. Matlab does this by calling the mex_tsctimer.dll generated by compiling this project file.
Wrapped TSCtime functions supported by this DLL are:
recalibrate();
gethectonanotime_first();
gethectonanotime_last();
A parameter is passed in from Matlab to select which wrapped function to invoke the desired TSCtime function avoiding the need for a separate DLL file for each function.
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
const char str[]="Function 'mexeval' not defined for variables of class";
char errMsg[100];
const mxArray *in_data;
int select = 0;
ULONGLONG t_meas = 0;
double *outArray;
if(nrhs==0) {
sprintf(errMsg,"%s '%s'\n",str,"double");
mexErrMsgTxt(errMsg);
}
else {
in_data = prhs[0];
select = (int)(mxGetScalar(prhs[0]));
if (select == 0) recalibrate();
else if (select == 1) t_meas = gethectonanotime_first();
else if (select == 2) t_meas = gethectonanotime_last();
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
outArray = mxGetPr(plhs[0]);
outArray[0] = ((double)t_meas)/1e7;
}
}
Installing the Matlab DLL
Simply copy the mex_tsctimer.dll into your Matlab installation and/or add the Release directory into your Windows path and you're ready to start using the timer.
Usage in Matlab
Before using the TSCtime functions in Matlab or in C/C++ for that matter, you will need to calibrate the timer using the TSCcal utility provided as part of Keith's distribution.
Again for those interested in the details of Keith's code, please refer to the excellent explanation on his website.
This utility writes the timer calibration data unique to your platform into the Windows registry which is subsequently read by the TSCtime routines to correct the timing information measured in user applications.
Here's an example of how to use the DLL to measure the runtime of a sparse matrix by vector multiplication in Matlab:
smvm_start = mex_tsctimer(1); % TSCtime : gethectonanotime_first()
b = A*x; % code whose execution time you want to measure
end_smvm= mex_tsctimer(2); % TSCtime : gethectonanotime_last()
run_time= end_smvm-smvm_start;