Click here to Skip to main content
Click here to Skip to main content

C++/Mex wrapper adds microsecond resolution timer to Matlab under WinXP

, 25 Aug 2005
Rate this:
Please Sign up or sign in to vote.
C++/Mex wrapper adds microsecond resolution timer to Matlab under WinXP.

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;

  //mexPrintf("executing mex_tsctimer(%d)\n", nrhs);
  //
  if(nrhs==0) {
    sprintf(errMsg,"%s '%s'\n",str,"double");
    mexErrMsgTxt(errMsg);
  }
  else { // causes MATLAB to execute the string as an expression
    //
    in_data = prhs[0];
    select = (int)(mxGetScalar(prhs[0]));
    //mexPrintf("%d selects %s\n", select, msg[select]);
    //
         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;
    //
    //mexPrintf("measured time %f = %f\n", 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;

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

moloned
Chief Technology Officer Movidius
Ireland Ireland
David Moloney holds a B.Eng. degree from Dublin City University, and Ph.D. in Engineering from Trinity College Dublin. For the past 25 years he has worked in microelectronics starting in 1985 with Infineon in Munich and ST Microelectronics in Milan, before returning to Ireland 1994 to help found a series of start-up technology companies including Parthus-CEVA and Silansys. David is currently co-founder (2005) and CTO of Movidius Ltd., a fabless semiconductor company headquartered in Dublin and focused on the design of software programmable multimedia accelerator SoCs. He holds 18 US patents and numerous conference and journal papers on DSP and computer architecture. David is a member of the IEEE.
Follow on   Twitter

Comments and Discussions

 
GeneralError in mex PinmemberAmitabh7777-Oct-09 8:31 
Generalerror with mex.h file PinmemberBoris40530-Apr-09 9:28 
Generalthx! plus a few corrections for msvs 2005 + Matlab 7.0 Pinmemberdain_bramage7-Nov-08 6:32 
Generala very simple way to acess a very high resolution timer [modified] Pinmembermjas12-Oct-06 16:49 
//add these few lines in your c++ code:
// first include this, if it isn't already included:
#include "stdafx.h"
 
// and declare some vars:
int m_Output = -1; // -1 if system doesn't support performance
LARGE_INTEGER start,stop;
LARGE_INTEGER freq;
 
// START: and here is the sample code at the place where to start:
 
QueryPerformanceCounter(&start); // acess the most higher timer in PC
 
// END: and at end this few lines compute the time spent so far:
 
QueryPerformanceCounter(&stop);
QueryPerformanceFrequency(&freq);
 
stop.QuadPart -= start.QuadPart; // subtract the initial time
stop.QuadPart *= 1000000; // (1000000)=microseconds (1000)=milliseconds (1000000000)=nanoseconds!
stop.QuadPart /= freq.QuadPart;
 
if (stop.HighPart != 0) m_Output = -1; // if overflow...
else m_Output = stop.LowPart;
 
NOTES:
if you want to measure the time spent for any block of code, you start that block with the first line (START), and after your code
you put those lines (END) for measuring the time spent. Easy!Smile | :)
 
Thank's to Sjaak Priester (author of this code), that he has implemented as a class.
 

-- modified at 22:57 Friday 13th October, 2006
GeneralError when compling Pinmembersmilurch8-Mar-06 18:01 
GeneralRe: Error when compling Pinmembermoloned8-Mar-06 20:39 
GeneralMissing download PinadminChris Maunder29-Aug-05 22:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 25 Aug 2005
Article Copyright 2005 by moloned
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid