Ich habe eine große Matrix und ich möchte sortperm
auf jede Spalte dieser Matrix anwenden. Die naive Sache zu tun istSpeicher-effiziente Sortierung auf einer Spalte einer Matrix
order = sortperm(X[:,j])
, die eine Kopie macht. Das scheint wie eine Schande, so dass ich dachte, ich würde versuchen, eine SubArray
:
order = sortperm(sub(X,1:n,j))
aber das war noch langsamer. Für ein Lachen habe ich versucht
order = sortperm(1:n,by=i->X[i,j])
aber natürlich war das schrecklich. Was ist der schnellste Weg, dies zu tun? Hier
ist einige Benchmark-Code:
getperm1(X,n,j) = sortperm(X[:,j])
getperm2(X,n,j) = sortperm(sub(X,1:n,j))
getperm3(X,n) = mapslices(sortperm, X, 1)
n = 1000000
X = rand(n, 10)
for f in [getperm1, getperm2]
println(f)
for it in 1:5
gc()
@time f(X,n,5)
end
end
for f in [getperm3]
println(f)
for it in 1:5
gc()
@time getperm3(X,n)
end
end
Ergebnisse:
getperm1
elapsed time: 0.258576164 seconds (23247944 bytes allocated)
elapsed time: 0.141448346 seconds (16000208 bytes allocated)
elapsed time: 0.137306078 seconds (16000208 bytes allocated)
elapsed time: 0.137385171 seconds (16000208 bytes allocated)
elapsed time: 0.139137529 seconds (16000208 bytes allocated)
getperm2
elapsed time: 0.433251141 seconds (11832620 bytes allocated)
elapsed time: 0.33970986 seconds (8000624 bytes allocated)
elapsed time: 0.339840795 seconds (8000624 bytes allocated)
elapsed time: 0.342436716 seconds (8000624 bytes allocated)
elapsed time: 0.342867431 seconds (8000624 bytes allocated)
getperm3
elapsed time: 1.766020534 seconds (257397404 bytes allocated, 1.55% gc time)
elapsed time: 1.43763525 seconds (240007488 bytes allocated, 1.85% gc time)
elapsed time: 1.41373546 seconds (240007488 bytes allocated, 1.82% gc time)
elapsed time: 1.42215519 seconds (240007488 bytes allocated, 1.83% gc time)
elapsed time: 1.419174037 seconds (240007488 bytes allocated, 1.83% gc time)
Wo die mapslices
Version 10x die getperm1
Version, wie man erwarten würde.
Es lohnt sich darauf hinzuweisen, dass die Option copy + sortperm auf meiner Maschine nicht viel langsamer ist als nur ein sortperm auf einem Vektor gleicher Länge, aber keine Speicherzuweisung ist notwendig, also wäre es nett um es zu vermeiden.
Wie funktioniert 'mapslices (sortperm, X, 1)'? – rickhg12hs
Hast du '@ time's für die' sortperm's, die du bisher probiert hast? – rickhg12hs