The most efficient way to create tensors from C++ for Python depends on which tensor library you're using. Here are the main approaches:
For NumPy Arrays
Use pybind11 with its built-in NumPy support. This allows zero-copy tensor creation:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
py::array_t<float> compute_tensor(size_t rows, size_t cols) {
// Allocate memory that will be owned by the NumPy array
auto result = py::array_t<float>({rows, cols});
auto buf = result.request();
float* ptr = static_cast<float*>(buf.ptr);
// Fill the data directly
for (size_t i = 0; i < rows * cols; i++) {
ptr[i] = /* your computation */;
}
return result;
}
PYBIND11_MODULE(mymodule, m) {
m.def("compute_tensor", &compute_tensor);
}
For PyTorch Tensors
Use torch::from_blob to wrap existing memory or create tensors directly:
#include <torch/extension.h>
torch::Tensor compute_tensor(int64_t rows, int64_t cols) {
// Option 1: Create tensor directly
auto options = torch::TensorOptions().dtype(torch::kFloat32);
torch::Tensor result = torch::empty({rows, cols}, options);
// Access raw data
float* data = result.data_ptr<float>();
for (int64_t i = 0; i < rows * cols; i++) {
data[i] = /* your computation */;
}
return result;
}
// Option 2: Wrap existing memory (be careful with lifetime!)
torch::Tensor wrap_existing_data(float* data, int64_t rows, int64_t cols) {
return torch::from_blob(data, {rows, cols}, torch::kFloat32);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("compute_tensor", &compute_tensor);
}
Key Optimization Strategies
-
Pre-allocate memory: Allocate the tensor once and fill it in-place rather than creating temporary buffers.
-
Use appropriate data types: Match your C++ computation type to the tensor dtype to avoid conversions.
-
Leverage parallelization: For large tensors, use OpenMP or parallel STL:
#pragma omp parallel for
for (int64_t i = 0; i < size; i++) {
data[i] = expensive_computation(i);
}
-
Memory alignment: For SIMD operations, ensure proper alignment:
// PyTorch tensors are already aligned
// For custom allocation with NumPy:
py::array_t<float, py::array::c_style | py::array::forcecast> result(
{rows, cols},
{cols * sizeof(float), sizeof(float)}, // strides
nullptr, // data pointer
py::dtype::of<float>()
);
-
Batch operations: If creating multiple tensors, consider returning a single larger tensor and reshaping in Python.
Python Side
Keep the Python side minimal:
import mymodule
import numpy as np
import torch
# NumPy
arr = mymodule.compute_numpy_tensor(100, 200) # Zero-copy
# PyTorch
tensor = mymodule.compute_torch_tensor(100, 200) # Already a tensor
# Convert between them efficiently
torch_from_numpy = torch.from_numpy(arr) # Shares memory
numpy_from_torch = tensor.numpy() # Shares memory if on CPU
The key is to create the tensor directly in C++ in the format you need, avoiding any intermediate copies or conversions. This approach gives you the best performance while maintaining clean interfaces between C++ and Python.