Is defining a function improves speed rather computing average for each analog input separately My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?
My code:
// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i&lt;sample_cnt;i++){
    avg_val += analogRead(analog_pin);        
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;  
  return avg_val;
  }
Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.
Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called &quot;unrolling the loop&quot;), so hand optimizing is probably not worthwhile.
Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.