-
Notifications
You must be signed in to change notification settings - Fork 41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Median (and presumably all quantile computation) could be much faster for large inputs #154
Comments
Interesting. Why not use this at least for large vectors. Regarding the performance of |
Note that the better answer here would be a QuickSelect based approach. partial sorting does more work than necessary here. |
Doesn't |
@nalimilan, yes. On 1.11.0-rc1 it uses BracketedSort (a generalization of the alg I proposed in this PR). However, I haven't closed this issue because another key optimization proposed here is that |
Can this implementation be used for |
partialsort(v::AbstractVector, k::Union{Integer,OrdinalRange}; kws...) =
partialsort!(copymutable(v), k; kws...) |
@aplavin, Yes, it is possible to make |
The concept is to take a random sample to quickly find values that almost certainly (99% chance) bracket target value(s), then efficiently pass over the whole input, counting values that fall above/below the bracketed range and explicitly storing only those that fall within the target range. If the median does not fall within the target range, try again with a new random seed up to three times (99.9999% success rate if the randomness is good). If the median does fall within the selected subset, find the exact target values within the selected subset.
Here's a naive implementation that is 4x faster for large inputs and allocates O(n ^ 2/3) memory instead of O(n) memory.
I think this is reasonably close to optimal for large inputs, but I payed no heed to optimizing the O(n^(2/3)) factors, so it is likely possible to optimize this to lower the crossover point where this becomes more efficient than the current median code.
This generalizes quite well to
quantiles(n, k)
for shortk
. It has a runtime ofO(n * k)
with a low constant factor. The calls topartialsort!
can also be replaced with more efficient recursive calls toquantile
Benchmarks
Runtimes measured in clock cycles per element (@ 3.49 GHz)
10^9 OOMs.
Benchmark code
And I removed the
length(x) < 2^12
fastpath to get accurate results for smaller inputs. I replaced the@assert
with1 <= lo_i || return median(v)
The text was updated successfully, but these errors were encountered: