Julia: Use same code path for `count(pred, itr)` as `sum(pred, itr)`

Created on 18 Feb 2017  路  5Comments  路  Source: JuliaLang/julia

count(pred, itr) (currently) has the same functionality as sum(pred, itr), only slower:

julia> function bench(N)
       r = randn(N)
       @time count(i->i>1.96, r)
       @time sum(i->i>1.96, r)
       end
bench (generic function with 1 method)

After warmup on latest master:

julia> bench(10^8)
 0.108136 seconds
  0.075002 seconds

We could just define count(pred, itr) = sum(pred, itr) ~but the count function just seems to be redundant~ (EDITED according to @ararslan's comment below and #20404 ).

This came up in
https://discourse.julialang.org/t/compute-number-of-values-in-an-array-above-a-threshold/2167

collections maths performance

Most helpful comment

Yes, I see what you mean; I hadn't seen #20404 before I posted.

In any case, count should not be 30% slower than sum in my example.

All 5 comments

I very much disagree with this. To reiterate what I said in https://github.com/JuliaLang/julia/issues/20404#issuecomment-277327841, should we make Bool not a subtype of Number (see #19168), it makes more sense to count non-numbers than to sum them, even if we do still define arithmetic on Bools. The functionality of sum and count overlaps in some cases, but I think in general they serve different purposes.

Yes, I see what you mean; I hadn't seen #20404 before I posted.

In any case, count should not be 30% slower than sum in my example.

On current master, count is nearly twice as slow on my machine:

julia> bench(10^8)
  0.104584 seconds
  0.059525 seconds

julia> 0.104584 / 0.059525
1.7569760604787903

This seems to be fixed on latest master:

julia> r = randn(10^8);

julia> @btime count(i->i>1.96, $r)
  57.402 ms (0 allocations: 0 bytes)
2499971

julia> @btime sum(i->i>1.96, $r)
  56.915 ms (0 allocations: 0 bytes)
2499971
Was this page helpful?
0 / 5 - 0 ratings

Related issues

StefanKarpinski picture StefanKarpinski  路  3Comments

i-apellaniz picture i-apellaniz  路  3Comments

TotalVerb picture TotalVerb  路  3Comments

arshpreetsingh picture arshpreetsingh  路  3Comments

ararslan picture ararslan  路  3Comments