Cleaner nested for loops in Cython without losing efficiency

Viewed 76

I'm writing optimized code in Cython that operates on a grid and often end up with constructions like this:

for i in range(n_boxes[0]):
    for j in range(n_boxes[1]):
        for k in range(n_boxes[2]):

Sometimes, there are even more nested for loops within the innermost loop.

The Pythonic way to avoid such ugly constructs would be something like

for i, j, k in itertools.product(*(range(n_boxes[dim]) for dim in n_boxes)):

but Cython can't optimize this into C for loops, which are much more efficient than calling out to Python, constructing tuples, unpacking tuples, etc.

How can I avoid the ugly nesting in the first example, and the excessive indentation that goes with it, while still allowing Cython to compile the code to a set of nested C for loops?

0 Answers
Related