Timer library (ProfileTimer) - times code on the Arduino

Posted by Nick Gammon on Wed 11 May 2011 02:49 AM — 5 posts, 50,172 views.

Australia Forum Administrator #0
I have adapted the "Timer" class presented elsewhere in the forum, for use on an Arduino. This will time any "batch" of code, by simply using a single line. For example, to time "something" I might do this:


{
ProfileTimer t ("testing something");
something ();
}


The interesting thing here is that the entire work is done in the ProfileTimer class constructor and destructor. The constructor makes a note of the current time, and echoes the "start" message.

The destructor makes a note of the (new) current time, subtracts the finish from the start, and displays the interval.

You can nest calls (see example program) so you can time smaller bits of code while still Timer the larger overall picture.

The purpose of the braces is to "scope" the ProfileTimer class so that when it hits the closing brace it goes out of scope and the destructor is called.

If you simply want to time an entire function, this is not necessary as the destructor is called when the function exits.

eg.


void myfunction (void)
  {
  ProfileTimer t ("myfunction");

  //  do something lengthy here

  }  // end of myfunction - time elapsed will be displayed


Or to save typing in the function name you can do this:


void myfunction ()
  {
  ProfileTimer t (__PRETTY_FUNCTION__);

  //  do something lengthy here
  
  }


The __PRETTY_FUNCTION__ argument returns the current function name, and its arguments.

In fact you can make a define to do that:


#define TIME_FUNCTION  ProfileTimer t (__PRETTY_FUNCTION__)


So now you can just to this:


void myfunction ()
  {
  TIME_FUNCTION;

  //  do something lengthy here
  
  }



The Arduino library can be downloaded from here:

http://www.gammon.com.au/Arduino/ProfileTimer.zip (4 Kb)

Unzip the file into your Arduino sketch "libraries" folder.

To use it just:


#include <ProfileTimer.h>


Example code that times analog reads:


#include <ProfileTimer.h>

void setup ()
{
  Serial.begin (115200);
}  // end setup

void readSensors ()
  {
 ProfileTimer t ("readSensors");

  int a = analogRead (A0);
  int b = analogRead (A1);
  }
  
void loop ()
{
  delay (500);

  ProfileTimer t ("analog read");
  analogRead (A1);

  {
    ProfileTimer t1 ("multiple reads");
    for (int i = A0; i <= A5; i++)
      analogRead (i);
  }  // end timed bit of code

}  // end loop


[EDIT] Renamed from Timer to ProfileTimer.
Amended on Thu 18 Aug 2011 10:03 PM by Nick Gammon
#1
hi,
the link for the library is not working, did you have another one?
USA Global Moderator #2
It looks like it was renamed to ProfileTimer. Try http://www.gammon.com.au/Arduino/ProfileTimer.zip
Australia Forum Administrator #3
Oops. Fixed original post.
#4
thanks!!!!