Skip to content

Instantly share code, notes, and snippets.

@stillyslalom
Last active November 15, 2015 06:20
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 stillyslalom/adfd514a6e856b6012ff to your computer and use it in GitHub Desktop.
Save stillyslalom/adfd514a6e856b6012ff to your computer and use it in GitHub Desktop.
Meshgrid vs. array broadcasting
using Plots
meshgrid(x,y) = (repmat(x',length(y),1),repmat(y,1,length(x)))
function test_meshgrid(n)
n = Int(n)
x = linspace(0,2pi,n); y = x
ret = zeros(n,n)
tic()
X, Y = meshgrid(x,y)
for j = 1:n
for i = 1:n
ret[i,j] = sin(X[i,j] + sin(Y[i,j]))
end
end
toc()
end
function test_broadcast(n)
n = Int(n)
x = linspace(0,2pi,n)'
y = x'
tic(); ret = sin(x .+ sin(y)); t = toc()
t
end
plot(floor(logspace(1,3)),[test_meshgrid,test_broadcast],
labels=["meshgrid","broadcast"]',title="elapsed time")
savefig(dirname(@__FILE__)*"\\mesh_v_broadcast")
meshalloc(n) = @allocated test_meshgrid(n)
broadalloc(n) = @allocated test_broadcast(n)
plot(floor(logspace(1,3)),[meshalloc,broadalloc],
labels=["meshgrid","broadcast"]',title="memory allocation")
savefig(dirname(@__FILE__)*"\\mesh_v_broadcast_malloc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment