Skip to content

Commit 9e103a2

Browse files
committed
improve performance for sparse matrix vector indexing (#29696)
(cherry picked from commit 0e023d0)
1 parent 51be362 commit 9e103a2

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

stdlib/SparseArrays/src/sparsematrix.jl

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2235,27 +2235,41 @@ function permute_rows!(S::SparseMatrixCSC{Tv,Ti}, pI::Vector{Int}) where {Tv,Ti}
22352235
colptrS = S.colptr; rowvalS = S.rowval; nzvalS = S.nzval
22362236
# preallocate temporary sort space
22372237
nr = min(nnz(S), m)
2238+
22382239
rowperm = Vector{Int}(undef, nr)
2239-
rowvalTemp = Vector{Ti}(undef, nr)
2240-
nzvalTemp = Vector{Tv}(undef, nr)
2240+
rowval_temp = Vector{Ti}(undef, nr)
2241+
rnzval_temp = Vector{Tv}(undef, nr)
2242+
perm = Base.Perm(Base.ord(isless, identity, false, Base.Order.Forward), rowval_temp)
22412243

22422244
@inbounds for j in 1:n
2243-
rowrange = colptrS[j]:(colptrS[j+1]-1)
2245+
rowrange = nzrange(S, j)
22442246
nr = length(rowrange)
2247+
resize!(rowperm, nr)
2248+
resize!(rowval_temp, nr)
22452249
(nr > 0) || continue
22462250
k = 1
22472251
for i in rowrange
22482252
rowA = rowvalS[i]
2249-
rowvalTemp[k] = pI[rowA]
2250-
nzvalTemp[k] = nzvalS[i]
2253+
rowval_temp[k] = pI[rowA]
2254+
rnzval_temp[k] = nzvalS[i]
22512255
k += 1
22522256
end
2253-
sortperm!(unsafe_wrap(Vector{Int}, pointer(rowperm), nr), unsafe_wrap(Vector{Ti}, pointer(rowvalTemp), nr))
2257+
2258+
if nr <= 16
2259+
alg = Base.Sort.InsertionSort
2260+
else
2261+
alg = Base.Sort.QuickSort
2262+
end
2263+
2264+
# Reset permutation
2265+
rowperm .= 1:nr
2266+
sort!(rowperm, alg, perm)
2267+
22542268
k = 1
22552269
for i in rowrange
22562270
kperm = rowperm[k]
2257-
rowvalS[i] = rowvalTemp[kperm]
2258-
nzvalS[i] = nzvalTemp[kperm]
2271+
rowvalS[i] = rowval_temp[kperm]
2272+
nzvalS[i] = rnzval_temp[kperm]
22592273
k += 1
22602274
end
22612275
end

0 commit comments

Comments
 (0)