# The quasi-best MaxN function

**URL:** <https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813>\
**Category:** Performance\
**Created:** [January 4, 2021, 9:32am UTC](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813 "2021-01-04T09:32:15Z")\
**Posts on this page:** 1\
**Showing post:** 13

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [January 6, 2021, 5:26pm UTC](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813/13 "2021-01-06T17:26:31Z")

</div>

Using some heap-functions and the suggestions of @mikkoku

```julia
function MaxN7(cr,N)
    maxn = heapify!(cr[1:N])
    maxn1=maxn[1]
       @inbounds for i in N+1:length(cr)
        e=cr[i]    
        if maxn1 < e
            heappop!(maxn)
            heappush!(maxn,e)
            maxn1=maxn[1]
            end
        end
    sort!(maxn,rev=true)
end

```

```julia
julia> nlargest(2000,re8)==MaxN7(re8,2000)
true

julia> @btime MaxN7($re6,20);
  576.800 μs (1 allocation: 240 bytes)

julia> @btime MaxN7($re8,2000);
  71.938 ms (1 allocation: 15.75 KiB)

julia> @btime nlargest(2000,$re8);
  86.122 ms (2 allocations: 31.50 KiB)

```

---

_[View the full topic](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813)._
