I tried to follow basic Performance Tips, but surprisingly, my Python code does it faster than Julia.
# Julia code
ʋ₀::Float64 = 1.0
r₀::Float64 = 1.0
n::Int64 = 5000000
const σ::Float64 = 1.0
const ϵ::Float64 = 1.0
const m::Float64 = 1.0
const Δt::Float64 = 1E-2
F = (r::Float64) -> -4*ϵ*(-12*σ^12/r^13 + 6*σ^6/r^7);
function md_model(ʋᵢ::Float64, rᵢ::Float64, n::Int64)
rʋ = Array{Float64, 2}(undef, n, 2)
for i = 1:n
ʋᵢ = ʋᵢ + Δt/2*(F(rᵢ)/m)
rᵢ₊₁ = rᵢ + Δt*ʋᵢ
ʋᵢ₊₁ = ʋᵢ + Δt/2*(F(rᵢ₊₁)/m)
rʋ[i, 1] = rᵢ = rᵢ₊₁
rʋ[i, 2] = ʋᵢ = ʋᵢ₊₁
end
return rʋ
end
I am using @btime to check the performance:
using BenchmarkTools
@btime md_model(ʋ₀, r₀, n);
This is the Python version:
import numpy as np
ʋ0 = 1.0
r0 = 1.0
n = 500000
σ = 1.0
ϵ = 1.0
m = 1.0
Δt = 1E-2
F = lambda r : -4*ϵ*(-12*σ**12/r**13 + 6*σ**6/r**7)
def md_model(ʋi, ri, n):
rʋ = np.empty((n, 2))
for i in range(n):
ʋi = ʋi + Δt/2*(F(ri)/m)
ri_new = ri + Δt*ʋi
ʋi_new = ʋi + Δt/2*(F(ri_new)/m)
ri = ri_new
ʋi = ʋi_new
rʋ[i, 0] = ri_new
rʋ[i, 1] = ʋi_new
return rʋ
# I am using %timeit to check the performance
%timeit md_model(ʋ0, r0, n)
The outputs in each case are:
Julia: 2.480990 seconds (50.01 M allocations: 839.939 MiB, 1.18% gc time, 0.59% compilation time)
Python: 824 ms ± 24.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
I also tried using @turbo in my Julia code, but it did not work (How could I implement it?).
Thank you for all the help,
Santiago