Skip to content

Instantly share code, notes, and snippets.

@JeffreySarnoff
Last active December 30, 2020 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffreySarnoff/4e194c89f7e21a51c23a7877f8a1fec7 to your computer and use it in GitHub Desktop.
Save JeffreySarnoff/4e194c89f7e21a51c23a7877f8a1fec7 to your computer and use it in GitHub Desktop.
notes on timing an example from twitter

re: https://twitter.com/SimonDeDeo/status/1344031423704006656

You are not timing the same thing in each language. See below for what you were timing in Julia.
And, as has been mentioned, use @time or @btime from BenchmarkTools.jl (time does not do what you expect it to do). When using @time, run the timing once to precompile the test before considering the results valid. The first run may take considerably longer, and that extra time is not computing time. I have omitted those lines below.

# this gets transformed into an array of Float64s 
julia> bb = [1, 2.0] 
2-element Array{Float64,1}:
 1.0
 2.0

# so, here we are timing promotions, allocations, and assignment
julia> @time for i in 1:100000; b=[1,2.0]; end
  0.150965 seconds (400.00 k allocations: 16.785 MiB)

# here we are timing allocations, and assignment
julia> @time for i in 1:100000; b=[1.0,2.0]; end
  0.002405 seconds (100.00 k allocations: 9.155 MiB)

# here we are timing the assignment only
julia>  bb = [1, 2.0];
julia> @time for i in 1:100000; b=bb; end
  0.000239 seconds # no allocations

# You can work with mixed type arrays,
#   to do that efficiently requires explict typing
julia> bb = Union{Int,Float64}[1, 2.0]
2-element Array{Union{Float64, Int64},1}:
 1
 2.0
 
# here we are timing the assignment only 
julia> @time for i in 1:100000; b=bb; end
  0.000216 seconds
  
# You can work with mixed type tuples,
#   they are efficient as given
julia> @time for i in 1:100000; b=(1,2.0); end
  0.000193 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment