# Code optimization a (simple) advection difference scheme

**URL:** <https://discourse.julialang.org/t/code-optimization-a-simple-advection-difference-scheme/24532>\
**Category:** Modelling & Simulations\
**Created:** [May 23, 2019, 6:07pm UTC](https://discourse.julialang.org/t/code-optimization-a-simple-advection-difference-scheme/24532 "2019-05-23T18:07:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fdevuyst](https://avatars.discourse-cdn.com/v4/letter/f/51bf81/32.png) [@fdevuyst](https://discourse.julialang.org/u/fdevuyst)\
**Post date:** [May 23, 2019, 6:07pm UTC](https://discourse.julialang.org/t/code-optimization-a-simple-advection-difference-scheme/24532/1 "2019-05-23T18:07:42Z")

</div>

Hi,

I’m beginner in Julia. I tried a simple code, but was a little bit disappointed with the performance. Could you give me hints in optimizing this snippet ?  
Kind regards, Florian

# 2D advection equation, periodic boundary conditions, explicit scheme, NxN grid

# 

using PyPlot

N = 800;  
u = zeros(N, N);  
h = 1.0 / N;  
x = h/2 : h : 1-h/2;  
y = x;  
X = x\*ones(1,N);  
Y = ones(N,1)\*y’;  
LEFT = [N; 1:N];  
RIGT = [1:N; 1];  
TOPP = RIGT;  
BOTT = LEFT;

# 

u = 0 .+ ((X.-0.5).^2 + (Y.-0.5).^2 .\< 0.125);

cfl = 0.49;  
ax = 1.0;  
ay = 1.0;  
umax = max(ax,ay);  
dt = cfl \* h / umax;  
figure(1);  
clf();

# 

for it = 0:1000  
phix = 0.5\*(ax_u[LEFT,:]+ax_u[RIGT,:]) - 0.5_abs(ax)_(u[RIGT,:] - u[LEFT,:]);  
phiy = 0.5\*(ay_u[:,BOTT]+ay_u[:,TOPP]) - 0.5_abs(ay)_(u[:,TOPP] - u[:,BOTT]);  
global u;  
u += - (dt/h) \* (phix[2:N+1,:] - phix[1:N,:]);  
u += - (dt/h) \* (phiy[:,2:N+1] - phiy[:,1:N]);  
if mod(it,100)==0  
clf();  
contour(u);  
pause(0.1);  
end  
end

#

---

<div class="post-metadata">

**Author:** ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)\
**Post date:** [May 23, 2019, 6:12pm UTC](https://discourse.julialang.org/t/code-optimization-a-simple-advection-difference-scheme/24532/2 "2019-05-23T18:12:35Z")

</div>

Welcome to the community! The first tip would be for you to study the [performance tips](https://docs.julialang.org/en/v1/manual/performance-tips/index.html) in the manual. The very first point would help you quite a lot.

---

<div class="post-metadata">

**Author:** ![fdevuyst](https://avatars.discourse-cdn.com/v4/letter/f/51bf81/32.png) [@fdevuyst](https://discourse.julialang.org/u/fdevuyst)\
**Post date:** [May 23, 2019, 6:43pm UTC](https://discourse.julialang.org/t/code-optimization-a-simple-advection-difference-scheme/24532/3 "2019-05-23T18:43:50Z")

</div>

Thank you for the link !
