You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
lexsort performance appears less than optimal #12755
A comment at the top of the implementation of PyArray_LexSort in item_selection.c indicates that lexsort is implemented by argsorting over the first key, then over the second key, and so on (which, I guess, explains the slightly curious argument order -- making the first argument the main sort key would have appeared more consistent with standard lexicographical ordering, but that's not the issue here).
The strategy appears to be less-than-optimal in the case where there are few ties in the "main" key (as one could probably just do a sort on the main key, and let the sort function look into secondary keys in the uncommon case of a tie).
But even sticking to the strategy used by lexsort (of sorting over each key successively), it looks like a pure-Python wrapper around argsort already does better:
# Make it so that there is a ~4-way tie for each primary key ("b"):
In [1]: N = 1000000; a = np.random.rand(N); b = np.random.randint(N // 4, size=N)
In [2]: def ls(a, b):
...: idxs = np.argsort(a, kind="stable")
...: return idxs[np.argsort(b[idxs], kind="stable")]
...:
In [3]: %timeit np.lexsort([a, b])
322 ms ± 944 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [4]: %timeit ls(a, b)
240 ms ± 580 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [5]: (np.lexsort([a, b]) == ls(a, b)).all()
Out[5]: True
Here the "pure Python" lexsort implementation is around 25% faster than lexsort.
Reproducing code example:
See above.
Error message:
N/A
Numpy/Python version information:
1.16.0 3.7.1 (default, Oct 23 2018, 19:19:42)
[GCC 7.3.0]
On a separate machine, I get a smaller difference but still in the same direction:
In [3]: %timeit np.lexsort([a, b])
386 ms ± 3.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [4]: %timeit ls(a, b)
362 ms ± 13.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Activity
Nicholas-Autio-Mitchell commentedon Apr 20, 2019
Running your test code, I get these results, with NumPy's
lexsortslightly outperforming base Python:charris commentedon Apr 20, 2019
Be interesting to see if things improve when 1.17 comes out with timsort as the default stable sorting algorithm.
eric-wieser commentedon Apr 20, 2019
Tested with 1.17-dev myself on windows, python 3.5 - difference between the two approaches is fairly negligeable.
And since we are doing argsort, the order probably doesn't affect memory access.
charris commentedon Apr 20, 2019
@eric-wieser Thought that might be the case. Oh well.
anntzer commentedon Apr 23, 2019
On a separate machine, I get a smaller difference but still in the same direction:
numpy 1.16.3, py 3.7, arch linux