diff --git a/src/data/Tensor.cpp b/src/data/Tensor.cpp index 6ab09620131726ee2af66450ce3bedc32ef90ca0..d45dee5639a6bc082871e1110657392fb97c15ec 100644 --- a/src/data/Tensor.cpp +++ b/src/data/Tensor.cpp @@ -45,10 +45,24 @@ void Aidge::Tensor::makeContiguous() { { // Create a new storage that will be contiguous std::shared_ptr<TensorImpl> newImpl = Registrar<Tensor>::create({mImpl->backend(), mDataType})(mImpl->device().second, mSize); - // Copy elements one by one from old to new storage - for (size_t idx = 0; idx < mSize; ++idx) { + // Copy elements from old to new storage + size_t idx = 0; + while (idx < mSize) { const size_t storageIdx = getStorageIdx(getCoord(idx)); - newImpl->copy(mImpl->rawPtr(mImplOffset + storageIdx), 1, idx); + + // Determine the size of the contiguous chunk + size_t copySize = 1; + while (idx + copySize < mSize && + getStorageIdx(getCoord(idx + copySize)) == storageIdx + copySize) + { + ++copySize; + } + + // Perform a single copy for the contiguous chunk + newImpl->copy(mImpl->rawPtr(mImplOffset + storageIdx), copySize, idx); + + // Move to the next index after the contiguous chunk + idx += copySize; } // Replace old storage by new, contiguous, storage setImpl(newImpl);