Having millions of numbers in a list, I want to take top K
occurrences. MMA Commonest
is very slow so I write my own versions:
a=RandomInteger[{1,1000000},50000000];
MyCommonest1[a_,n_]:=Take[SortBy[Tally[a],Last],-n]
MyCommonest2[a_,n_]:=(b=Tally[a];Take[b[[Reverse[Ordering[b[[All,2]]]]]],n])
MyCommonest3[a_,n_]:=(b=Tally[a];b[[Take[Ordering[b[[All,2]]],-n]]])
MyCommonest4[a_,n_]:=Take[SortBy[Tally[a],-#[[2]]&],n]
Timings:
1.68
1.12
1.15
1.70
Can it be any faster?
Edit
The C# counterpart of this problem in SO is here.