14

I need to determine the speed with which Arduino executes a certain function.

What would be the best time to do that? So far I found something with a Stopwatch class, but I'm wondering if there's any native method to do that.

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Eugen
  • 1,537
  • 7
  • 29
  • 57

2 Answers2

25

A straightforward way is to use the millis() or micros() function in the Arduino library. You will have a finer grain result with micros().

For instance:­­­­­­

unsigned long start = micros();
// Call to your function
myFunction();
// Compute the time it took
unsigned long end = micros();
unsigned long delta = end - start;
Serial.println(delta);

Read carefully the documentation of micros(): there are some information about the time resolution.

Msprg
  • 199
  • 2
  • 11
Vincent Hiribarren
  • 5,254
  • 2
  • 41
  • 65
  • don't forget to time the 'micros' function before to remove its calltime from the result, it could be significant. unsigned long m1 = micros(); unsigned long m2 = micros(); unsigned long mt = m2 - m1; ... unsigned long delta = end - start - mt; – Ugo Robain Mar 26 '14 at 10:57
  • @UgoRobain This seems like a good idea at first, but it's inherently flawed to try and remove the error from a timing function by timing it using itself. – krb686 Jun 29 '14 at 05:12
  • 2
    Could you elaborate ? I don't see why calling 'micros' twice and substracting the results would not give me the time taken by micros. if you call this before doing your function's timing you can subtract two times the 'micros' duration and therefore achieve to get a more precise timing of myFunction. – Ugo Robain Jul 11 '14 at 17:00
  • One time the 'micros' duration, sorry. – Ugo Robain Jul 11 '14 at 17:07
14

the least intrusive way is to set a port pin high before the function call and low afterwards. Put an oscilloscope on the port pin and measure the high-time.

This can also give you a good qualitative idea of the variability of execution time by triggering on the rising edge and watching the jitter on the falling edge.

Martin Thompson
  • 16,395
  • 1
  • 38
  • 56
  • Thanks a lot. Yes, I did use an osciloscope, but for other purposes. The problem is I have to be able to use that variable in my program. – Eugen Apr 26 '12 at 19:09