Skip to content

Optimization: Replace loop with bvec[:, indices] for slicing rows #2

@SaFE-APIOpt

Description

@SaFE-APIOpt

new_dir = np.take(x, indices)

Current code:

dirs = []
for x in bvec:
    new_dir = np.take(x, indices)
    dirs.append(new_dir)
new_bvec = np.stack(dirs, axis=0)

Suggested replacement:
new_bvec = bvec[:, indices]
The current implementation loops over all rows in bvec, calling np.take on each one, and appends results to a list before stacking. This introduces significant overhead from:

Python-level iteration;

Repeated function calls;

Intermediate list and array construction.

The optimized version uses NumPy’s advanced indexing to extract the desired columns from all rows at once:

It is fully vectorized, much faster, and more memory efficient;

The result is exactly the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions