Author Topic: Repeated function calls in statement - Bad practice?  (Read 14909 times)

0 Members and 1 Guest are viewing this topic.

Online PsiTopic starter

  • Super Contributor
  • ***
  • Posts: 12793
  • Country: nz
Repeated function calls in statement - Bad practice?
« on: March 17, 2016, 06:57:04 am »
Quick question.

Do you think this is bad practice?

Code: [Select]
uint32 BattADC_AVG = ( (MeasureBattADC() + MeasureBattADC() + MeasureBattADC() + MeasureBattADC() ) >> 2);
My reasoning is that some odd compiler might optimize out the repeated calls and use the same value?
Or should that never happen?
Greek letter 'Psi' (not Pounds per Square Inch)
 

Offline Boomerang

  • Regular Contributor
  • *
  • Posts: 53
Re: Repeated function calls in statement - Bad practice?
« Reply #1 on: March 17, 2016, 07:02:16 am »
This may happen if you have some way to declare the function as "deterministic".
 

Offline Ian.M

  • Super Contributor
  • ***
  • Posts: 14140
Re: Repeated function calls in statement - Bad practice?
« Reply #2 on: March 17, 2016, 07:23:33 am »
As each function call is a sequence point, assuming MeasureBattADC() accesses at least one volatile object, any compiler that reorders or eliminates them is broken. 

There's a nasty trap here if the actual ADC read is interrupt driven and the function doesn't use volatile variables or other thread-safe method of receiving the data from the ISR, as if it doesn't access a volatile, write memory or produce other side-effects, the compiler cannot determine that the function's execution could produce a different result to that the abstract machine would produce executing it literally the first time, so would be free to re-order or eliminate the repeated function calls.   That wouldn't be because your expression above invoking the function is dangerous, it would be because you have written a broken function.
« Last Edit: March 17, 2016, 04:41:36 pm by Ian.M »
 

Offline Brutte

  • Frequent Contributor
  • **
  • Posts: 614
Re: Repeated function calls in statement - Bad practice?
« Reply #3 on: March 17, 2016, 07:26:50 am »
Do you think this is bad practice?

Code: [Select]
uint32 BattADC_AVG = ( (MeasureBattADC() + MeasureBattADC() + MeasureBattADC() + MeasureBattADC() ) >> 2);
It is impossible to debug because the debugger would have stepped over this line in single step. Besides, it unrolls a loop which is a bad practice by itself. I'd use do{}while() and #define ADC_AVG_FILTER_EXP2 2.
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3671
  • Country: gb
Re: Repeated function calls in statement - Bad practice?
« Reply #4 on: March 17, 2016, 07:54:19 am »
Why not put the averaging into the MeasureBattADC() function?  If required you could pass an argument to set the number of readings to be averaged.
 

Online mikeselectricstuff

  • Super Contributor
  • ***
  • Posts: 14861
  • Country: gb
    • Mike's Electric Stuff
Re: Repeated function calls in statement - Bad practice?
« Reply #5 on: March 17, 2016, 08:02:13 am »
There is no such thing as good or bad practice, only more or less appropriate for a particular situation.
A compiler would never optimise multiple calls like that, as at some point the function would access variables declared volatile (typically the ADC's hardware registers).
It would break if the function simply returned the last known ADC value from a free-running continuous conversion process without waiting for a new reading, but that's not a compiler issue.

 
Youtube channel:Taking wierd stuff apart. Very apart.
Mike's Electric Stuff: High voltage, vintage electronics etc.
Day Job: Mostly LEDs
 

Offline tszaboo

  • Super Contributor
  • ***
  • Posts: 9942
  • Country: nl
  • Current job: ATEX product design
Re: Repeated function calls in statement - Bad practice?
« Reply #6 on: March 17, 2016, 08:16:32 am »
But why no a for loop. Makes it debuggable and shorter.
Measure power rails with 2GHz bandwidt: https://eleshop.eu/prp1-power-rail-probe.html
 

Offline bitseeker

  • Super Contributor
  • ***
  • Posts: 9057
  • Country: us
  • Lots of engineer-tweakable parts inside!
Re: Repeated function calls in statement - Bad practice?
« Reply #7 on: March 17, 2016, 08:44:08 am »
Agreed. Unless the overhead of a do or for loop is unacceptably high for your particular use case, unrolling it like that is unusual.
TEA is the way. | TEA Time channel
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: Repeated function calls in statement - Bad practice?
« Reply #8 on: March 17, 2016, 09:51:38 am »
This may happen if you have some way to declare the function as "deterministic".

that is the first feature I have implemented in my "safeC" language
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: Repeated function calls in statement - Bad practice?
« Reply #9 on: March 17, 2016, 02:56:59 pm »
My reasoning is that some odd compiler might optimize out the repeated calls and use the same value?
Or should that never happen?
Sure it could happen. Depends on the definition of MeasureBattADC().

If your function simply returns a constant and the definition is "seen" in the current compilation unit, then any compiler worth it's salt would replace all the calls with the constant and evaluate the whole thing at compile time.

OTOH, if the function accesses volatile memory (or has volatile inline assembly) which prevents the compiler from optimizing, it'll do what you intend.
 

Offline suicidaleggroll

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
Re: Repeated function calls in statement - Bad practice?
« Reply #10 on: March 17, 2016, 03:27:19 pm »
Why not put the averaging into the MeasureBattADC() function?  If required you could pass an argument to set the number of readings to be averaged.

Agreed.  Add an input to the function to control the number of iterations, and then stick a for loop inside.
 

Offline AndyC_772

  • Super Contributor
  • ***
  • Posts: 4612
  • Country: gb
  • Professional design engineer
    • Cawte Engineering | Reliable Electronics
Re: Repeated function calls in statement - Bad practice?
« Reply #11 on: March 17, 2016, 03:32:57 pm »
IMHO, doing (or not doing) something in code for no better reason than someone says it's good (or bad) practice, is bad practice.

Offline djacobow

  • Super Contributor
  • ***
  • Posts: 1183
  • Country: us
  • takin' it apart since the 70's
Re: Repeated function calls in statement - Bad practice?
« Reply #12 on: March 17, 2016, 04:14:41 pm »
Certainly, no C or C++ compiler would optimize out calls like that, but I wonder if there are other languages that can identify if a function is idempotent and automatically memoize it. Of course, such a language would not be popular with system programmers. :-)

Note that you can have functions that are idempotent, even though they touch hardware or volatile state. Imagine a missile class with methods: fuel(), arm(), and launch(). Obviously you can call launch() as many times as you like, but only the first time will do something interesting. The others methods could be coded that way, too.
 

Online westfw

  • Super Contributor
  • ***
  • Posts: 4676
  • Country: us
Re: Repeated function calls in statement - Bad practice?
« Reply #13 on: March 17, 2016, 05:31:43 pm »
Quote
Why not put the averaging into the MeasureBattADC() function?
I also agree.  Or a separate function "MeasureAvgBattV()"
I don't see anything wrong with the repeated function calls.  Well, aside from it probably being annoyingly slow - I'd prefer ADCs to be sampled by ISRs and/or DMA with running-averages maintained automatically, so that the actual "getADC" call is essentially instantaneous.  In which case calling it four times in a row wouldn't be helpful.
 

Offline grumpydoc

  • Super Contributor
  • ***
  • Posts: 3038
  • Country: gb
Re: Repeated function calls in statement - Bad practice?
« Reply #14 on: March 17, 2016, 07:55:47 pm »
Quick question.

Do you think this is bad practice?

Code: [Select]
uint32 BattADC_AVG = ( (MeasureBattADC() + MeasureBattADC() + MeasureBattADC() + MeasureBattADC() ) >> 2);
My reasoning is that some odd compiler might optimize out the repeated calls and use the same value?
Or should that never happen?

I suppose the question is - why do you want to do it that way and what is really wrong with

uint32 BattADC_AVG =  MeasureBattADC();

BattADC_AVG += MeasureBattADC();
BattADC_AVG += MeasureBattADC();
BattADC_AVG += MeasureBattADC();
BattADC_AVG /= 4;


Which will probably generate the same code and is easier to read.

Thought 1 - is uint32 the correct type for MeasureBattADC(), AtoD's generally produce signed values don't they?

Thought 2 - using >> 2 instead of / 4 might be slightly faster but it's probably the worst bit of bad practice in your original statement. Unless you have proven that you need to save the execution time go for clarity. And if you do need to save the execution time say why in a comment. In fact there is at least some chance that the compiler will optimise a "divide by constant power of 2" to a shift for you anyway.

 

Offline djacobow

  • Super Contributor
  • ***
  • Posts: 1183
  • Country: us
  • takin' it apart since the 70's
Re: Repeated function calls in statement - Bad practice?
« Reply #15 on: March 17, 2016, 08:19:16 pm »
Thought 2 - using >> 2 instead of / 4 might be slightly faster but it's probably the worst bit of bad practice in your original statement. Unless you have proven that you need to save the execution time go for clarity. And if you do need to save the execution time say why in a comment. In fact there is at least some chance that the compiler will optimise a "divide by constant power of 2" to a shift for you anyway.

Not even. gcc is clever enough to convert division of integers by power-of-two literals with shifts. However, for signed numbers >> 2 and / 4 may not give the same answer.

Code: [Select]
#include <stdio.h>

int foo(int a) {
 return a / 4;
}
int bar(int a) {
 return a >> 2;
}

int main(int argc, char *argv[]){
 printf("%d\n",foo(-1));
 printf("%d\n",bar(-1));
 return 0;
}

On myLLVM 7.0.3 gives:

Code: [Select]
0
-1


You can see that in the assembly, they both use shifts, but for the division there is more work to make sure that shifting -1 to the right gets you zero, rather than just perpetual negative ones.

Code: [Select]
.section __TEXT,__text,regular,pure_instructions
.macosx_version_min 10, 10
.globl _foo
.align 4, 0x90
_foo:                                   ## @foo
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp0:
.cfi_def_cfa_offset 16
Ltmp1:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp2:
.cfi_def_cfa_register %rbp
movl %edi, %eax
sarl $31, %eax
shrl $30, %eax
addl %edi, %eax
sarl $2, %eax
popq %rbp
retq
.cfi_endproc

.globl _bar
.align 4, 0x90
_bar:                                   ## @bar
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp3:
.cfi_def_cfa_offset 16
Ltmp4:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp5:
.cfi_def_cfa_register %rbp
sarl $2, %edi
movl %edi, %eax
popq %rbp
retq
.cfi_endproc


Not pasting it here, but for unsigneds you get the identical code.

« Last Edit: March 17, 2016, 08:21:39 pm by djacobow »
 

Offline grumpydoc

  • Super Contributor
  • ***
  • Posts: 3038
  • Country: gb
Re: Repeated function calls in statement - Bad practice?
« Reply #16 on: March 17, 2016, 08:46:17 pm »
Not even. gcc is clever enough to convert division of integers by power-of-two literals with shifts.

I'm having slight difficulty parsing your comment so I'm not sure whether you are agreeing with me or not :)

Your posted example shows that gcc will happily convert divide by constant power of 2 to a shift. With ints code is added to the divide case to handle the sign but the actual division is a shift.

Quote
Not pasting it here, but for unsigneds you get the identical code.

Indeed, it produces completely identical code:


unsigned int t1(unsigned int a)
{
  return a / 4;
}

unsigned int t2(unsigned int a)
{
  return a >> 2;
}


Compiled -O2 yields


   .file   "test.c"
   .text
   .p2align 4,,15
.globl t1
   .type   t1, @function
t1:
   pushl   %ebp
   movl   %esp, %ebp
   movl   8(%ebp), %eax
   popl   %ebp
   shrl   $2, %eax
   ret
   .size   t1, .-t1
   .p2align 4,,15
.globl t2
   .type   t2, @function
t2:
   pushl   %ebp
   movl   %esp, %ebp
   movl   8(%ebp), %eax
   popl   %ebp
   shrl   $2, %eax
   ret
   .size   t2, .-t2
   .ident   "GCC: (GNU) 4.4.7 20120313 (Red Hat 4.4.7-3)"
   .section   .note.GNU-stack,"",@progbits


Which is the same code, using a shift, for both functions

Quote
However, for signed numbers >> 2 and / 4 may not give the same answer.
Which is why gcc generates slightly different code for the two cases.

MISRA bans (or advises against) shifts with integers doesn't it?

Which, by the way, is another reason to write divide when you mean divide - suppose the code starts out with uint but someone later changes it (lets assume with good reason) to int - the shift might be a long way from the declaration so could be missed, introducing a subtle bug. If the code had used divide no such bug would get introduced.
 

Offline SL4P

  • Super Contributor
  • ***
  • Posts: 2318
  • Country: au
  • There's more value if you figure it out yourself!
Re: Repeated function calls in statement - Bad practice?
« Reply #17 on: March 17, 2016, 11:34:47 pm »
My only problem with any of these suggestions is the average is taken over the period of 'n' back-to-back samples... hardly an average.  I would expect any number of samples to be taken over a longer period, or rolling average methodology to eliminate short term variations.

Just sayin'  I know it's not the point of the OP question.
Don't ask a question if you aren't willing to listen to the answer.
 

Offline Sal Ammoniac

  • Super Contributor
  • ***
  • Posts: 1816
  • Country: us
Re: Repeated function calls in statement - Bad practice?
« Reply #18 on: March 18, 2016, 12:03:04 am »
MISRA bans (or advises against) shifts with integers doesn't it?

There's nothing in MISRA C:2004 that precludes the use of shifts. The only requirement related to shifts is

Quote
Rule 12.8 (required) The right-hand operand of a shift operator shall lie between zero and one less than the
width in bits of the underlying type of the left-hand operand.
"That's not even wrong" -- Wolfgang Pauli
 

Offline djacobow

  • Super Contributor
  • ***
  • Posts: 1183
  • Country: us
  • takin' it apart since the 70's
Re: Repeated function calls in statement - Bad practice?
« Reply #19 on: March 18, 2016, 12:30:31 am »
I was agreeing. I mean, it is not any slower to use the divide, so you might as well. It's clearer.
« Last Edit: March 18, 2016, 12:34:19 am by djacobow »
 

Online PsiTopic starter

  • Super Contributor
  • ***
  • Posts: 12793
  • Country: nz
Re: Repeated function calls in statement - Bad practice?
« Reply #20 on: March 18, 2016, 01:09:06 am »
Thanks everyone, lots of useful comments.

The function just starts an ADC conversion, waits for it to finish and returns the value. Not using interrupts, (yeah I know it should be).

There is a long running average that also uses this read function periodically.
But in this case I just needed a custom read at that exact time for a special case, and wanted to reduce error a little.

Will change it to use repeated += and / for better debugging and clarity
Greek letter 'Psi' (not Pounds per Square Inch)
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2862
  • Country: nz
Re: Repeated function calls in statement - Bad practice?
« Reply #21 on: March 18, 2016, 01:57:32 am »
Do you think this is bad practice?

Code: [Select]
uint32 BattADC_AVG = ( (MeasureBattADC() + MeasureBattADC() + MeasureBattADC() + MeasureBattADC() ) >> 2);

Ignoring the context given by the choice of variable and function names, this code can't handle the entire range of values returned by the function (assuming it returned a uint32). It may be preferable to use:

Code: [Select]
uint32 a = f()/4 + f()/4 + f()/4 + f()/4;
This would not fail when f() returns an average value greater than 0x40000000.

If you were concerned about the loss of the low two bits they could be tracked separately. Something like:
Code: [Select]
uint32 a;
unit32 low_bits;
for(i = 0; i < 4; i++) {
   uint32 s = f();
   low_bits += s&3;
   a += s/4;
}
a += low_bits/4;

If you are calling this function regularly to assess the battery, you could also do something like this to only perform one reading at a time;
Code: [Select]
   uint32 s0;
   static uint32 s1, s2, s3=0;
   uint32 BattADC_AVG
   if(s3 == 0) {
      /* First time we have read the battery voltage */
     /* Assuming function never returns 0 */
      s0 = MeasureBattADC();
      s1 = MeasureBattADC();
      s2 = MeasureBattADC();
   } else {
      /* Move samples along */
      s0 = s1;
      s1 = s2;
      s2 = s3;
   }
   s3 = MeasureBattADC();
   BattADC_AVG = s0/4 + s1/4 + s2/4 + s3/4;
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline djacobow

  • Super Contributor
  • ***
  • Posts: 1183
  • Country: us
  • takin' it apart since the 70's
Re: Repeated function calls in statement - Bad practice?
« Reply #22 on: March 18, 2016, 04:11:03 am »
(recommendation for sliding window average)

Hamster's reco is a good one.

I also like the classic first-order low-pass IIR, which consumes no memory other than storing the average. This compares favorably with big window filters if you desire a lot of smoothing and space is tight -- isn't it always?

y[n] = a*x[n] + (1-a)x[n-1]

https://en.wikipedia.org/wiki/Exponential_smoothing

Here's one implementation (C++) with an example use, coded somewhat carefully to be flexible and still get you code with no multiplies or divides in it -- if you pick your constants carefully.

Code: [Select]
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

// This class implements a simple EMA filter. That is
//
// y[n] = a * x[n] + (1-a) * y[n-1]
//
// Because we seek to be fixed-point friendly, we
// define:
//
// a = ALPHA / DENOM
//
// Where both ALPHA < DENOM so that 0 < a < 1.
//
// However, to get the compiler to emit efficient code,
// and particularly, code completely free of multiplies,
// and divides, choose ALPHA and DENOM that are
// powers of two, such as 1 and 256.
//
// Also, to get the compiler to use shifts instead of multiplies,
// it must see the filter constants as literals rather than
// variables. That's why this is a template.
//
// The state variable of this filter is essentially always
// left-shifted by DENOM,  so the larger the DENOM you choose,
// say, for more filtering, will also use up some upper bits
// of the state variable, so your range will be reduced.
//
// One solution to this is to use a larger type for the
// state variable. Of course, you could also use fp types,
// too. The types are parameterized in this template for that
// purpose. 

template <typename SAMP_TYPE, typename STORE_TYPE,
      uint32_t ALPHA, uint32_t DENOM>
class ema_c {
 public:
  ema_c() { };

  // not strictly necessary, but you can 'prime' the
  // filter with the first sample
  void init(SAMP_TYPE sample) {
    state = sample * DENOM;
  }

  // call every time you have a new sample, returns the
  // current average
  SAMP_TYPE update(SAMP_TYPE sample) {
    state = (
              (ALPHA * sample) +

              state -

              ((ALPHA * state) / DENOM)
            );

    return (state / DENOM);
  }

 private:
  STORE_TYPE state;
};


int main(int argc, char *argv[]) {

  typedef int32_t sample_t;

  const int32_t alpha = 1;
  const int32_t denom = 64;
  // instantiate filter
  ema_c<sample_t, sample_t, alpha, denom> filter;

  // prime filter to 0 -- not really necessary
  filter.init(0);

  int32_t ct = 0;
  // create a noisy square wave, and watch the filter track it.
  while (ct < 10000) {
    int32_t r   = ((ct/1000)%2) * 5000 + (10000 * rand() / RAND_MAX);
    int32_t avg = filter.update(r);
    printf("%d,%d\n", r, avg);
    ct++;
  }
  return 0;
}

I know folks don't like C++ much for low-level coding, but I've found that once you get the hang of using it carefully, it's actually pretty good for the task. Templates are just macros with more features.

The output of this looks something like this:
« Last Edit: March 18, 2016, 07:37:34 pm by djacobow »
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: Repeated function calls in statement - Bad practice?
« Reply #23 on: March 18, 2016, 04:13:39 pm »
I know folks don't like C++ much for low-level coding, but I've found that once you get the hang of using it carefully, it's actually pretty good for the task.
IMO, C++ is actually *better* than straight C for low-level coding, but that's a topic for another fist-fight.  :o

I'm using a EWMA template quite similar to yours. The main difference is that my alpha is just a const member (not a template parameter) and that I pre-compute 1-alpha. Here's the operative part:

Code: [Select]
    /**
     * @brief recalculates the average for a new input sample
     * @param sample the new value
     * @return new average including the new input sample
     */
    T operator()(T sample) {
        accumulator_ =
          ((alpha_ * sample) + (one_minus_alpha_ * accumulator_) / Scale);
        return (*this)();
    }

EDIT: I think the moving average approach works better when you're constantly sampling something at a steady rate. Then you can set alpha to 1/(sample_rate + R*C + 1) and have the EWMA simulate a low-pass RC filter. However, if you're sampling at odd intervals (as you might for reading a battery level), the filtering will confuse things.
« Last Edit: March 18, 2016, 04:21:37 pm by andyturk »
 

Offline djacobow

  • Super Contributor
  • ***
  • Posts: 1183
  • Country: us
  • takin' it apart since the 70's
Re: Repeated function calls in statement - Bad practice?
« Reply #24 on: March 18, 2016, 05:35:14 pm »
IMO, C++ is actually *better* than straight C for low-level coding, but that's a topic for another fist-fight.  :o

Took me awhile to get there, but I'm on board.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->