Skip to content

C++ <-> Python conversion performance #3

Open
@benbovy

Description

@benbovy

I did a quick benchmark to evaluate the overhead of C++ -> Python conversion:

py::array_t<PyObjectGeography> create(py::array_t<double> xs, py::array_t<double> ys) {
    py::buffer_info xbuf = xs.request(), ybuf = ys.request();

    auto result = py::array_t<PyObjectGeography>(xbuf.size);
    py::buffer_info rbuf = result.request();

    double *xptr = static_cast<double *>(xbuf.ptr);
    double *yptr = static_cast<double *>(ybuf.ptr);
    py::object *rptr = static_cast<py::object *>(rbuf.ptr);

    py::gil_scoped_release();
    for (size_t i = 0; i < xbuf.shape[0]; i++) {
        auto point_ptr = PointFactory::FromLatLonDegrees(xptr[i], yptr[i]);
        
        // either one or the other of the two code lines below are commented out.
        // "cast" benchmark (calls py::cast)
        rptr[i] = py::cast(std::move(point_ptr));
        // or
        // "no_cast" benchmark (just create an empty python object)
        rptr[i] = py::object()
    }

    return result;

...

m.def("create", &create);

Here are the results:

x = np.random.rand(10_000)
y = np.random.rand(10_000)

# "cast" benchmark
%timeit s2shapely.create(x, y)
# 12.6 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# "no cast" benchmark
%timeit s2shapely.create(x, y)   
# 4.46 ms ± 156 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The cast version is almost 3x slower than the no cast version. That's a lot for "just" wrapping the C++ geography in a Python object. Not sure what's happening (the Geography (sub)classes only implement move semantics, so there shouldn't be any data copy at this level), but there must be something wrong.

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