2

In Cython, is there a way to achieve compile time evaluation of a condition? For example something like

def func(bint value):
    cdef int i
    for i in range(1000000):
        # Some stuff is calculated
        if value:
            # Do something...
        else:
            # Do something else...

Is there a way to tell Cython to create two versions of the function, one for value==True and one for value==False? The evaluation of the if-statement in each loop iteration could have measurable performance costs otherwise.

Padix Key
  • 857
  • 6
  • 15
  • 1
    Cython has `IF` and `DEF` to pick code at compile time (eg https://stackoverflow.com/questions/47276648/cython-precompiler-decision-making/47292793#47292793) but I don't think that's quite what you're after. – DavidW Feb 22 '18 at 15:39
  • This is the kind of optimization that a good C compiler will probably do by itself anyway though – DavidW Feb 22 '18 at 15:40

1 Answers1

1

To @DavidW's comment, there is a decent chance the compiler recognizes and optimizes this by itself. Comparable example on godbolt here - it seems the check is lifted with -O3, not with -O2 on the particular GCC I'm using.

double func(bool value) {
    double accum = 0.0;
    for (int i = 0; i < 100000; ++i) {
        if (value) {
            accum += 0.05;
        } else {
            accum += 0.10;
        }
    }
    return accum;
}

If you want to guarantee the check is lifted out of the loop, you obviously could manually lift out, though that presumably leads to code duplication.

If value is truly known at compile time, with c++ you could use templates or if constexpr (c++17) to generate compile time specializations.

You would also have the option of using C macros to help manage the duplication. IMO not worth the nastiness unless really performance critical, but it's there.

chrisb
  • 49,833
  • 8
  • 70
  • 70