Last active
November 15, 2015 06:20
-
-
Save stillyslalom/adfd514a6e856b6012ff to your computer and use it in GitHub Desktop.
Meshgrid vs. array broadcasting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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