I couldn't find anything yet - is there a recommended / fastest way to get the number of bits in a number (I really only need it for unsigned values).Thanks
…or ceil(Int, log(2, x)) if you want the number of bits required to represent x as an unsigned integer.
It really depends on what you mean by “the number of bits in a number” :P
// T
Well, I asked about how to get it as fast as possible.Turns out, leading_zeros does just what I want, using the lzcnt* instruction :-)If you don't count the unnecessary frame setup (pushq %rbp; movq %rsp, %rbp) and frame pop/return (popq %rbp ; ret), the whole thing I want boils down to 4 instructions, nicely parameterized by Julia on the type ;-)
julia> f1(x) = sizeof(x)<<3 - leading_zeros(x)
f1 (generic function with 1 method)
julia> f2(x) = ceil(log2(x))
f2 (generic function with 1 method)
julia> f3(x) = length(bin(x))
f3 (generic function with 1 method)
julia> function f4(x)
n = 0
while x != 0
n += 1
x >>= 1
end
n
end
f4 (generic function with 1 method)
julia> ft1(x,n) = (local y ; for i=1:n ; y = f1(x) ; end ; y)
ft1 (generic function with 1 method)
julia> ft2(x,n) = (local y ; for i=1:n ; y = f2(x) ; end ; y)
ft2 (generic function with 1 method)
julia> ft3(x,n) = (local y ; for i=1:n ; y = f3(x) ; end ; y)
ft3 (generic function with 1 method)
julia> ft4(x,n) = (local y ; for i=1:n ; y = f4(x) ; end ; y)
ft4 (generic function with 1 method)
julia> @time ft1(x,1000000)
0.006164 seconds (4 allocations: 160 bytes)
32
julia> @time ft2(x,1000000)
0.024435 seconds (1.00 M allocations: 15.259 MB, 8.07% gc time)
31.0
julia> @time ft3(x,1000000)
0.070985 seconds (2.00 M allocations: 122.070 MB, 7.80% gc time)
32
julia> @time ft4(x,1000000)
0.027962 seconds (4 allocations: 160 bytes)
3