Time the Execution of a Short Piece of Code

For timing short intervals, you can use this timer #1 quick and dirty technique: Clear the timer, start then stop it. Read the value of the counter, it will be in cycles (times prescaler). This is particularly useful for profiling execution of code. Understand this will trash timer1, which in the arduino is used for the Servo library.

  TCCR1B = 1;
  TCNT1 = 0;
  //insert code to be profiled here
  TCCR1B = 0;
  printf("Cycles=%d\n\r", TCNT1);

Remember to set the prescaler if necessary. The prescale can be set to 1, 8, 64, 256 or 1024, and at 16MHz:

Prescale  Time per counter tick
1          0.0625uS
8          0.500uS
64         4.000uS
256       16.000uS
1024      64.000uS

Time per Tick = (Prescale)*(1/Frequency)

About Jim Eli

µC experimenter
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s