From d79d9d7a5bb1d46d49d4c66d523890fb4749ff63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=83=A1=E6=99=A8=E5=AE=87?= <12410918@mail.sustech.edu.cn> Date: Sun, 31 May 2026 11:07:12 +0800 Subject: [PATCH] parallelize sort_ using parallel_for_ --- modules/core/src/matrix_operations.cpp | 71 ++++++++++++++------------ 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/modules/core/src/matrix_operations.cpp b/modules/core/src/matrix_operations.cpp index 043820c375..6ca7168bf5 100644 --- a/modules/core/src/matrix_operations.cpp +++ b/modules/core/src/matrix_operations.cpp @@ -992,7 +992,6 @@ namespace cv template static void sort_( const Mat& src, Mat& dst, int flags ) { - AutoBuffer buf; int n, len; bool sortRows = (flags & 1) == SORT_EVERY_ROW; bool inplace = src.data == dst.data; @@ -1001,44 +1000,48 @@ template static void sort_( const Mat& src, Mat& dst, int flags ) if( sortRows ) n = src.rows, len = src.cols; else - { n = src.cols, len = src.rows; - buf.allocate(len); - } - T* bptr = buf.data(); - - for( int i = 0; i < n; i++ ) + parallel_for_(Range(0, n), [&](const Range& range) { - T* ptr = bptr; - if( sortRows ) - { - T* dptr = dst.ptr(i); - if( !inplace ) - { - const T* sptr = src.ptr(i); - memcpy(dptr, sptr, sizeof(T) * len); - } - ptr = dptr; - } - else - { - for( int j = 0; j < len; j++ ) - ptr[j] = src.ptr(j)[i]; - } - - std::sort( ptr, ptr + len ); - if( sortDescending ) - { - for( int j = 0; j < len/2; j++ ) - std::swap(ptr[j], ptr[len-1-j]); - } - + AutoBuffer buf; if( !sortRows ) - for( int j = 0; j < len; j++ ) - dst.ptr(j)[i] = ptr[j]; - } + buf.allocate(len); + T* bptr = buf.data(); + + for( int i = range.start; i < range.end; i++ ) + { + T* ptr = bptr; + if( sortRows ) + { + T* dptr = dst.ptr(i); + if( !inplace ) + { + const T* sptr = src.ptr(i); + memcpy(dptr, sptr, sizeof(T) * len); + } + ptr = dptr; + } + else + { + for( int j = 0; j < len; j++ ) + ptr[j] = src.ptr(j)[i]; + } + + std::sort( ptr, ptr + len ); + if( sortDescending ) + { + for( int j = 0; j < len/2; j++ ) + std::swap(ptr[j], ptr[len-1-j]); + } + + if( !sortRows ) + for( int j = 0; j < len; j++ ) + dst.ptr(j)[i] = ptr[j]; + } + }); } + #ifdef HAVE_IPP typedef IppStatus (CV_STDCALL *IppSortFunc)(void *pSrcDst, int len, Ipp8u *pBuffer);