What's the best way to time a function in VC++?

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

What's the best way to time a function in VC++?

Post by Shane » Fri Jul 31, 2009 2:29 pm

Dear all,

I'm using clock() command at the moment to findthe time spent on a time critical function.
But I'm not satisfied with the output. Do you know a better way to find it with more accuracy?

Regards,

Shane
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: What's the best way to time a function in VC++?

Post by Neo » Fri Jul 31, 2009 3:33 pm

Hi Shane,

Yes, there are few methods for this. clock() function is not accurate at all.
Refer the following table.

Average Error(ms) Resolution (Error x 2) (ms)
clock () 27 55
_ftime () 27 55
GetTickCount () 10 20
Multimedia Timer 1 2


So GetTickCount and Multimedia Timer are the most accurate ways to do this.
Have a look at the following examples.
GetTickcount
===========

Code: Select all

#include <windows.h>
#include <stdio.h>

void main (void){

  DWORD i, st, en, diff;
  
  for (i = 100; i < 130; i++){

      st = GetTickCount ();
      while (GetTickCount () < (st + i));
      en = GetTickCount ();
      diff = en - st;
      printf ("Expected:%d  Actual:%ld\n", i, diff);

    }
}
Multimedia Timer (winmm.lib)
=========================

Code: Select all

#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>

void main (void){

  TIMECAPS res;
  DWORD i, st, en, diff;

  if (timeGetDevCaps (&res, sizeof (TIMECAPS)) == TIMERR_NOERROR){
      printf ("Supported min resolution = %d\n", res.wPeriodMin);
      printf ("Supported max resolution = %d\n", res.wPeriodMax);
  }

  if (res.wPeriodMin <= 1){

      if (timeBeginPeriod (1) == TIMERR_NOERROR){

          for (i = 100; i < 130; i++){
             st = timeGetTime ();
             while (timeGetTime () < (st + i));
             en = timeGetTime ();
             diff = en - st;
             printf ("Expected:%d  Actual:%ld\n", i, diff);
          }

          timeEndPeriod (1);
      }
  }
}
When you see the output, you will agree that Multimedia Timer method is the most acurate one.
Hope this helps.

Regards,

Neo
    User avatar
    Shane
    Captain
    Captain
    Posts: 226
    Joined: Sun Jul 19, 2009 9:59 pm
    Location: Jönköping, Sweden

    Re: What's the best way to time a function in VC++?

    Post by Shane » Fri Jul 31, 2009 3:44 pm

    Multimedia Timer has sorted out my problem.

    Thanks a lot.

    Shane
    Post Reply

    Return to “C/C++ Programming”