Skip to content

Replace np.fromiter with np.asarray when input is a list #1

@SaFE-APIOpt

Description

@SaFE-APIOpt

cs838/main.py

Line 122 in 70d64da

y_vals = np.fromiter(iter(data), dtype=float)

Current code:

data = [q[index] for q in raw_data]
y_vals = np.fromiter(iter(data), dtype=float)

Proposed replacement:

data = [q[index] for q in raw_data]
y_vals = np.asarray(data, dtype=float)

In this context, data is already a Python list. Wrapping it in iter() and using np.fromiter adds unnecessary overhead because fromiter has to consume the iterator element by element and build the array from scratch.

np.asarray can directly convert the list into a NumPy array, producing the same result with less overhead.

Performance: Benchmarks show that for list inputs, np.asarray consistently outperforms np.fromiter. Additionally, if the input is already a NumPy array with the same dtype, asarray can even return a view instead of copying, further improving efficiency

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