Measure how many clock cycles a function takes to execute

Hi!

I want to measure how many clock cycles a function takes to execute. That way I would now how many MHz a program actually needs.

I tried using avr-objdump and the document "AVR 8-bit Instruction Set" to count clocks for each instruction.

Is there any better ways? Does it exists any utilty that count instructions/clocks for a program or function?

/Olof

What, are you planning to put in a slower crystal?

You could call micros() at the start of the function, call it again at the end, and subtract one result from another, to get a rough estimate. Not sure how useful that really is though.

olof_n: I tried using avr-objdump and the document "AVR 8-bit Instruction Set" to count clocks for each instruction.

That would only really help if the function didn't have any loops (or call other functions).

Thanks for the reply Nick!

Ok, so It will not work with loops, to bad.

I was curious because it would be great to know If my program could use the 8MHz internal oscillator instead of a external 16MHz crystal. I call a multiplex function every 1000 micros and it would be great to know how much "CPU time" a have left.

Set a pin high before you call the function and low after. Measure the pulse width with a scope or logic analyser.

If you don't have those instruments buy one :) (or use Nick's micros() suggestion).


Rob

Set a pin high before you call the function and low after.

Preferably, using direct port manipulation, to minimise overhead

olof_n: I call a multiplex function every 1000 micros and it would be great to know how much "CPU time" a have left.

Take the delays out and see how fast it goes?

I use this kind of loop.

unsigned long start = millis();
for(int i=0; i<10000; i++)
{
   f();
}
unsigend long stop = millis();
Serial.println((stop-start)*1.6);

using 10000 calls prevents the 4usec stepsize of micros() - OK it also counts the loop increments, the compare and jumps(? ticks)

The *1.6 gives approx nr of clockcycles

suppose it takes 100 millis() to complete 10000 calls then 1 call = 160 ticks = 10 micros

I have a scope so I can try and measure the time or try the software solutions you have proposed.

To speed up the code I use digitalWriteFast. I don't think that speed is an issue In my program but I was curious how many "MHz" would be enough.

Thank you all.