I am trying to understand why is numpy's cumsum function so much faster than a manual c++ loop. I am using pybind to provide mapping from C++'s code to python.
Numbers first:
[nav] In [24]: x = np.arange(100_000, dtype=np.float32)
[nav] In [25]: %timeit np.cumsum(x)
295 µs ± 34.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
[ins] In [26]: %timeit derived.cumsum(x)
9.26 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Now how is derived.cumsum(x) obtained?
template <typename Sequence,
typename = std::enable_if_t<std::is_rvalue_reference_v<Sequence&&>>>
inline py::array_t<typename Sequence::value_type> as_pyarray(Sequence&& seq) {
auto size = seq.size();
auto data = seq.data();
auto seq_ptr = std::make_unique<Sequence>(std::move(seq));
auto capsule = py::capsule(seq_ptr.get(), [](void* p) {
std::unique_ptr<Sequence>(reinterpret_cast<Sequence*>(p));
});
seq_ptr.release();
return py::array(size, data, capsule);
}
std::vector<float> cumsum(const std::vector<float>& nums) {
std::vector<float> result(nums.size());
float sum = 0;
for (size_t i = 0; i < nums.size(); ++i) {
sum += nums[i];
result[i] = sum;
}
return result;
}
PYBIND11_MODULE(derived, m) {
m.def("cumsum", [](const std::vector<float>& nums) {
auto result = cumsum(nums);
return as_pyarray(std::move(result));
});
}
as_pyarray was obtained from this pybind issue which ensures zero copy when interacting between python and c++.
Note that C++ code was compiled with -O3 -DNDEBUG -fPIC.