Electronic – arduino – Monitor clock cycles for code on arduino/AVR

arduinoatmelavrtimer

Is it possible to monitor a block of code and determine the number of processor clock cycles that code took on an Arduino and/or AVR atmel processor? or, should I rather monitor microseconds passed before and after code run? Note: I'm not concerned with real time (as in, how many real seconds passed) as much as I am in "how many clock cycles does this code require from the CPU"

The current solution I can come up with is from time.c:

#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )

wiring.c adds:

#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

By this account i could calculate clock cyles passed by monitoring microseconds passed and then pass that to microsecondsToClockCycles(). My question is, is there a better way?

sidenote: are there good resources for performance monitoring of the AVR. lmgtfy.com and various forums searches do not provide any obvious results, other than exploration of timers

thanks

Best Answer

The simplest method is to make your code pull some pin up before it executes the code you want to time, and pull it low after it has finished doing whatever. Then make the code loop (or use digital oscilloscope with memory in single-shot mode) and just scope then pin. The length of the pulse tells you how long it took to execute the piece of code plus one clock cycle from changing the pin state (I think it takes one cycle, not 100% sure).