Skip to content

Commit 2224afb

Browse files
committed
examples: add performance benchmark with matlab
1 parent 06ef620 commit 2224afb

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

examples/benchmark_w_matlab.jl

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2+
# # Comparing the performance of the Julia and MATLAB implementations
3+
4+
# We can compare the performance of the Julia and MATLAB implementations by running the same model for the same number of epochs and measuring the time taken.
5+
6+
using BeforeIT, Plots, Statistics
7+
8+
parameters = BeforeIT.AUSTRIA2010Q1.parameters
9+
initial_conditions = BeforeIT.AUSTRIA2010Q1.initial_conditions
10+
T = 12*2
11+
12+
# We will run the model without any output to avoid the overhead of printing the results.
13+
function run_no_output(;multi_threading = false)
14+
model = BeforeIT.initialise_model(parameters, initial_conditions, T)
15+
data = BeforeIT.initialise_data(model);
16+
17+
for _ in 1:T
18+
BeforeIT.one_epoch!(model; multi_threading = multi_threading)
19+
BeforeIT.update_data!(data, model)
20+
end
21+
end
22+
23+
# we run the code to compile it fist
24+
@time run_no_output()
25+
@time run_no_output(;multi_threading = true)
26+
27+
# time taken by the MATLAB code, computed independently on an Apple M1 chip
28+
matlab_times = [3.1465, 3.0795, 3.0274, 3.0345, 3.0873]
29+
matlab_time = mean(matlab_times)
30+
matlab_time_std = std(matlab_times)
31+
32+
# time taken by the Julia code, computed as the average of 5 runs
33+
n_runs = 5
34+
35+
julia_times_1_thread = zeros(n_runs)
36+
for i in 1:n_runs
37+
julia_times_1_thread[i] = @elapsed run_no_output()
38+
end
39+
julia_time_1_thread = mean(julia_times_1_thread)
40+
julia_time_1_thread_std = std(julia_times_1_thread)
41+
42+
43+
julia_times_multi_thread = zeros(n_runs)
44+
for i in 1:5
45+
julia_times_multi_thread[i] = @elapsed run_no_output(multi_threading = true)
46+
end
47+
julia_time_multi_thread = mean(julia_times_multi_thread)
48+
julia_time_multi_thread_std = std(julia_times_multi_thread)
49+
50+
# get the number of threads used
51+
n_threads = Threads.nthreads()
52+
53+
# bar chart of the time taken vs the time taken by the MATLAB code, also plot the stds as error bars
54+
bar(["MATLAB", "Julia, 1 thread", "Julia, $n_threads threads"], [matlab_time, julia_time_1_thread, julia_time_multi_thread], yerr = [matlab_time_std, julia_time_1_thread_std, julia_time_multi_thread_std], legend = false, dpi=300)
55+
ylabel!("Time for one simulation (s)")
56+
57+
# the Julia implementation is faster than the MATLAB implementation, and the multi-threaded version is faster than the single-threaded version.
58+
59+
# save the image
60+
savefig("benchmark_w_matlab.png")

0 commit comments

Comments
 (0)