0

I'm trying to write a C++ extension for image processing. My images are quite large: 2064x1543 for example. I found that it takes a long time to just pass this via the binding. Here's a minimal reproducible example:

I have a C++ file called example.cpp.:

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

void doNothing(std::vector<std::vector<std::array<double, 3>>> arr) {}

PYBIND11_MODULE(example, m) { m.def("doNothing", &doNothing);}

From which I export a Python extension with

g++ -Wall -fPIC -shared example.cpp $(python3 -m pybind11 --includes) -O3 -o example$(python3-config --extension-suffix)

I have a test.py to time it:

from time import time
import numpy as np
from example import doNothing

arr = np.random.uniform(size=(1543, 2064, 3))

start = time()
doNothing(arr)
print(time() - start)

Which comes out to around 0.5 s on my machine. Seems like a long time! Am I doing something wrong? Can this be sped up?

My context: I've been using Python for years but totally new to C++

Alexander Soare
  • 2,825
  • 3
  • 25
  • 53
  • PS if you are wondering why I am using float64 for the array, it's because I lied about this being an image. It's really an ordered point cloud. – Alexander Soare Feb 15 '22 at 13:39
  • 9
    You are passing by value, so the entire data needs to be copied first. This can indeed be slow – UnholySheep Feb 15 '22 at 13:42
  • @UnholySheep I just changed my the argument type for the C++ function to be `py::array_t` (from [here](https://stackoverflow.com/questions/63009472/pybind11-passing-numpy-array-to-c-by-value-reference)) and it seems to have done the trick. Thanks for the lead. Happy to accept a response if you care to put it together. – Alexander Soare Feb 15 '22 at 13:47

0 Answers0