Ceiling division

x ÷ k is faster than floor(Int, x/k). Is there an ceiling division function that rounds up instead of down, equivalent to but faster than ceil(Int, x/k)?

julia> f(x) = floor(Int, x/4)
f (generic function with 1 method)

julia> g(x) = x÷4
g (generic function with 1 method)

julia> @benchmark f(x) setup = (x=rand())
BenchmarkTools.Trial: 10000 samples with 1000 evaluations.
 Range (min … max):  6.422 ns … 29.276 ns  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     6.432 ns              ┊ GC (median):    0.00%
 Time  (mean ± σ):   6.535 ns ±  0.661 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%

  █                                                           
  █▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▁▂▂▁▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ ▂
  6.42 ns        Histogram: frequency by time        10.4 ns <

 Memory estimate: 0 bytes, allocs estimate: 0.

julia> @benchmark g(x) setup = (x=rand())
BenchmarkTools.Trial: 10000 samples with 999 evaluations.
 Range (min … max):  8.234 ns … 15.023 ns  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     8.244 ns              ┊ GC (median):    0.00%
 Time  (mean ± σ):   8.269 ns ±  0.241 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%

                            ▁ █                            ▅  
  ▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█▁█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▇▁█ ▂
  8.23 ns        Histogram: frequency by time        8.25 ns <

 Memory estimate: 0 bytes, allocs estimate: 0.

yes, there is :slight_smile:
https://docs.julialang.org/en/v1/base/math/#Base.cld

3 Likes