How to truncate decimal points and convert to an integer in Julia
Overview
To use the trunc
function, simply pass Int
as the first argument.
Code
julia> @time for t in 1:10^8
Int64(ceil(t/1000))
end
0.189653 seconds
julia> @time for t in 1:10^8
trunc(Int64, ceil(t/1000))
end
0.128472 seconds
The two loops perform the identical task but with about a 1.5 times speed difference. The former drops the decimal points using ceil
and type casts to Int64
, whereas the latter returns an integer natively using the built-in capability of the trunc
function, which is faster.
People who are used to programming in other languages might find the straightforward commands like the upper loop more intuitive, but in Julia, there are many built-in functions that take a data type as the first argument to return a result, so the usage like in the lower loop will become more familiar.
Environment
- OS: Windows
- julia: v1.5.0