using BenchmarkTools
zvec, δvec = randn(10000) * 1e-2, randn(10000) * 1e-3
# Physical constant
const restenergy = 0.511e6
const clight = 3e8
# Computation settings
nturns = 10001
# Machine parameter
struct Par
v1::Float64
v2::Float64
ϕs::Float64
ϕ2s::Float64
h1::Int64
h::Int64
circum::Float64
centerenergy::Float64
αc::Float64
r::Float64
end
function Par(v1, v2, ϕs, ϕ2s, h1, h, circum, centerenergy, αc)
Par(v1, v2, ϕs, ϕ2s, h1, h, circum, centerenergy, αc, v2 / v1)
end
function _revolution_cache(p::Par)
c1 = p.v1 / p.centerenergy
c2 = sin(p.ϕs) + p.r * sin(p.ϕ2s)
c3 = 1 / (p.centerenergy / restenergy)^2
k1 = 2 * p.h1 * pi / p.circum
k2 = 2 * p.h1 * p.h * pi / p.circum
(; c1, c2, c3, k1, k2)
end
function revolution_with_cache(z::Number, δ::Number, p::Par, c)
δ = δ + c.c1 * (sin(p.ϕs - c.k1 * z) + p.r * sin(p.ϕ2s - c.k2 * z) - c.c2)
η = p.αc - c.c3 / (1 + δ)^2
z = z - p.circum * η * δ
z, δ
end
function revolution!(zvec::Vector, δvec::Vector, nturns::Int64, p::Par)
c = _revolution_cache(p)
nparticles = length(zvec)
@inbounds for j = 1:nturns
@inbounds @simd for i = 1:nparticles
zvec[i], δvec[i] = revolution_with_cache(zvec[i], δvec[i], p, c)
end
end
zvec, δvec
end
p = Par(3.6395053705870048e+06, 655751.6971214055228756, 2.1575815005097385, 6.0620746573056303, 756, 3, 1360.4, 6e9, 1.56e-5)
@btime revolution!($zvec, $δvec, $nturns, $p);
Hello everyone. I’m trying to modify this code faster than MATLAB.
zvec = randn(10000,1) * 1e-2;
deltavec = randn(10000,1) * 1e-3;
%%
restenergy = 0.511e6;
clight = 3e8;
nturns = 10001;
nparticle = length(zvec);
v1 = 3.6395053705870048e+06;
v2 = 655751.6971214055228756;
r = v2/v1;
phi_s = 2.1575815005097385;
phi_2s = 6.0620746573056303;
h1 = 756;
h = 3;
circum = 1360.4;
centerenergy = 6e9;
alpha_c = 0.0000156;
%%
tic;
for i = 1:nturns
deltavec = deltavec + v1/centerenergy * (sin(phi_s - 2 * h1 * pi / circum .* zvec) - sin(phi_s) + r * sin(phi_2s - 2 * h1 * h * pi / circum .* zvec) - r * sin(phi_2s));
etavec = alpha_c - 1./(centerenergy/restenergy .* (1 + deltavec)).^2;
zvec = zvec - circum .* etavec .* deltavec;
end
toc
On my computer, the Julia code runs for approximately 1.73 seconds, while the MATLAB code runs for 0.63 seconds.
How else can I optimize the code to double or triple its speed?