Skip to content

Replace interp1d(kind='zero') with np.searchsorted for better performance #1

@SaFE-APIOpt

Description

@SaFE-APIOpt

func = interp1d(xp, yp, kind='zero', fill_value='extrapolate', assume_sorted=False)

Hi, thank you for the great work!
In the following code:

func = interp1d(xp, yp, kind='zero', fill_value='extrapolate', assume_sorted=False)
return np.where(np.asanyarray(x) < xmin, left, func(x))

Suggested Optimization

ix = np.searchsorted(xp, x, side='right') - 1
func = lambda x: yp[ix]

This replacement removes the need for interp1d, avoids Python-level function dispatch, and leverages NumPy’s highly optimized searchsorted for efficient zero-order hold interpolation.
This approach is not only faster but also more memory-efficient, and still preserves the original extrapolation behavior using np.where.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions