Skip to content

Commit cc64d5d

Browse files
authored
Merge pull request #43 from jalvesz/benchmarks
Benchmarks
2 parents 64f4540 + 3529846 commit cc64d5d

17 files changed

Lines changed: 681 additions & 1 deletion

‎.github/workflows/docs.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ on:
2828
# reference reads the sources.
2929
- 'src/**'
3030
- 'examples/**'
31+
- 'benchmarks/**'
3132
- 'fpm.toml'
3233
pull_request:
3334
paths: *paths
@@ -107,6 +108,13 @@ jobs:
107108
sphinx-build --version
108109
ford --version
109110
111+
# Adds benchmarks/results/github-actions.json, which docs/conf.py renders
112+
# on the benchmarks page. Not committed; timings from the CI runner.
113+
- name: Run benchmarks
114+
run: |
115+
pip install -r benchmarks/requirements.txt
116+
python benchmarks/run_benchmarks.py --repeats 5 --save github-actions
117+
110118
- name: Build Docs
111119
env:
112120
# Picked up by docs/conf.py as fplotlib_gallery_compiler.

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,7 @@ __pycache__/
2424
docs/_build/
2525
docs/auto_gallery/
2626
docs/sg_execution_times.rst
27+
28+
# generated docs content
29+
docs/_generated/
30+
benchmarks/results/github-actions.json

‎benchmarks/animation.f90‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
program bench_animation
2+
use fplotlib
3+
implicit none
4+
integer, parameter :: n = 240, n_frames = 40
5+
real(dp), parameter :: pi = 3.14159265358979323846_dp
6+
real(dp) :: x(n), y(n), envelope(n), phase
7+
integer :: frame, i
8+
9+
do i = 1, n
10+
x(i) = 10.0_dp*real(i - 1, dp)/real(n - 1, dp)
11+
end do
12+
envelope = exp(-0.15_dp*x)
13+
14+
do frame = 1, n_frames
15+
phase = 2.0_dp*pi*real(frame - 1, dp)/real(n_frames, dp)
16+
y = sin(2.0_dp*x - phase)*envelope
17+
call clf()
18+
call plot(x, y, "b-", lw=2.0_dp)
19+
call fill_between(x, y, color="b", alpha=0.2_dp)
20+
call xlim(0.0_dp, 10.0_dp)
21+
call ylim(-1.1_dp, 1.1_dp)
22+
call title("Travelling wave")
23+
call xlabel("x")
24+
call ylabel("displacement")
25+
call grid(.true.)
26+
call add_frame()
27+
end do
28+
call save_animation("animation_f.gif", fps=20.0_dp)
29+
end program bench_animation

‎benchmarks/animation.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import sys
2+
import time
3+
import matplotlib
4+
matplotlib.use("Agg")
5+
import matplotlib.pyplot as plt
6+
import numpy as np
7+
from matplotlib.animation import FuncAnimation, PillowWriter
8+
9+
10+
def main(ext="gif"):
11+
n_frames = 40
12+
x = np.linspace(0, 10, 240)
13+
envelope = np.exp(-0.15*x)
14+
fig, ax = plt.subplots()
15+
16+
# Every frame is cleared and redrawn, like clf() + plot() in the Fortran program.
17+
def draw(frame):
18+
ax.clear()
19+
y = np.sin(2*x - 2*np.pi*frame/n_frames)*envelope
20+
ax.plot(x, y, "b-", lw=2)
21+
ax.fill_between(x, y, color="b", alpha=0.2)
22+
ax.set_xlim(0, 10)
23+
ax.set_ylim(-1.1, 1.1)
24+
ax.set_title("Travelling wave")
25+
ax.set_xlabel("x")
26+
ax.set_ylabel("displacement")
27+
ax.grid(True)
28+
29+
anim = FuncAnimation(fig, draw, frames=n_frames)
30+
anim.save("animation_py." + ext, writer=PillowWriter(fps=20))
31+
32+
33+
if __name__ == "__main__":
34+
t0 = time.perf_counter()
35+
main(*sys.argv[1:2])
36+
print(f"RUN_SECONDS {time.perf_counter() - t0:.6f}")

‎benchmarks/complex.f90‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
program bench_complex
2+
use fplotlib
3+
implicit none
4+
integer, parameter :: n = 5000
5+
real(dp) :: x(n), y1(n), y2(n), y3(n)
6+
integer :: i
7+
character(len=:), allocatable :: ext
8+
character(len=16) :: arg
9+
10+
ext = "png"
11+
if (command_argument_count() > 0) then
12+
call get_command_argument(1, arg)
13+
ext = trim(arg)
14+
end if
15+
do i = 1, n
16+
x(i) = 20.0_dp*real(i - 1, dp)/real(n - 1, dp)
17+
y1(i) = sin(x(i))*exp(-0.1_dp*x(i))
18+
y2(i) = cos(2.0_dp*x(i))*exp(-0.05_dp*x(i))
19+
y3(i) = 0.5_dp*sin(0.5_dp*x(i))
20+
end do
21+
call plot(x, y1, "b-", label="damped sin", lw=2.0_dp)
22+
call plot(x, y2, "r--", label="damped cos")
23+
call plot(x, y3, "g-", label="slow sin")
24+
call fill_between(x, y1, y2, alpha=0.2_dp)
25+
call title("Complex benchmark")
26+
call xlabel("time")
27+
call ylabel("amplitude")
28+
call grid(.true.)
29+
call legend()
30+
call savefig("complex_f." // ext)
31+
end program bench_complex

‎benchmarks/complex.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import sys
2+
import time
3+
import matplotlib
4+
matplotlib.use("Agg")
5+
import matplotlib.pyplot as plt
6+
import numpy as np
7+
8+
def main(ext="png"):
9+
x = np.linspace(0, 20, 5000)
10+
y1 = np.sin(x)*np.exp(-0.1*x)
11+
y2 = np.cos(2*x)*np.exp(-0.05*x)
12+
y3 = 0.5*np.sin(0.5*x)
13+
plt.plot(x, y1, "b-", label="damped sin", lw=2)
14+
plt.plot(x, y2, "r--", label="damped cos")
15+
plt.plot(x, y3, "g-", label="slow sin")
16+
plt.fill_between(x, y1, y2, alpha=0.2)
17+
plt.title("Complex benchmark")
18+
plt.xlabel("time")
19+
plt.ylabel("amplitude")
20+
plt.grid(True)
21+
plt.legend()
22+
plt.savefig("complex_py." + ext)
23+
24+
if __name__ == "__main__":
25+
t0 = time.perf_counter()
26+
main(*sys.argv[1:2])
27+
print(f"RUN_SECONDS {time.perf_counter() - t0:.6f}")

‎benchmarks/render_results.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""Turn benchmarks/results/*.json into a Markdown page with collapsible tables.
2+
3+
Used by docs/conf.py, so the docs always show whatever is in the results
4+
folder. Usage: python benchmarks/render_results.py OUTPUT.md
5+
"""
6+
import html
7+
import json
8+
import sys
9+
from pathlib import Path
10+
11+
RESULTS = Path(__file__).resolve().parent / "results"
12+
MACHINE_LABELS = [
13+
("cpu", "CPU"), ("cpu_ghz", "Clock speed (GHz)"), ("os", "OS"),
14+
("fortran_compiler", "Fortran compiler"), ("fortran_flags", "Fortran flags"),
15+
("fpm", "fpm"), ("python", "Python"), ("matplotlib", "Matplotlib"),
16+
("numpy", "NumPy"),
17+
]
18+
19+
20+
def e(x):
21+
return html.escape(str(x))
22+
23+
24+
def section(path, data):
25+
m = data["machine"]
26+
out = [f"<details><summary><b>{e(m.get('cpu', path.stem))}</b> &mdash; "
27+
f"{e(m.get('os', ''))} &mdash; {e(data.get('date', ''))} "
28+
f"(<code>{e(path.name)}</code>)</summary>", "<h4>Machine</h4>", "<table>"]
29+
for key, label in MACHINE_LABELS:
30+
if m.get(key) is not None:
31+
out.append(f"<tr><th>{label}</th><td>{e(m[key])}</td></tr>")
32+
out.append("</table>")
33+
out.append(f"<h4>Results (median of {e(data.get('repeats', '?'))} runs)</h4>")
34+
out.append("<table><tr><th>Benchmark</th><th>fplotlib (s)</th>"
35+
"<th>matplotlib (s)</th></tr>")
36+
results = {}
37+
for r in data["results"]:
38+
variant = r["variant"]
39+
if variant.startswith(("fplotlib", "Fortran compile")):
40+
column = "fplotlib"
41+
elif variant.startswith(("matplotlib", "Python imports")):
42+
column = "matplotlib"
43+
else:
44+
raise ValueError(f"Unknown benchmark variant: {variant}")
45+
timings = results.setdefault(r["benchmark"], {})
46+
if column in timings:
47+
raise ValueError(f"Duplicate {column} result for {r['benchmark']}")
48+
timings[column] = f"{r['seconds']:.4f}"
49+
for benchmark, timings in results.items():
50+
out.append(f"<tr><td>{e(benchmark)}</td><td>{timings.get('fplotlib', '')}</td>"
51+
f"<td>{timings.get('matplotlib', '')}</td></tr>")
52+
out.append("</table></details>")
53+
return "\n".join(out)
54+
55+
56+
def render():
57+
blocks = []
58+
for path in sorted(RESULTS.glob("*.json")):
59+
blocks.append("```{raw} html\n" + section(path, json.loads(path.read_text()))
60+
+ "\n```\n")
61+
if not blocks:
62+
return "*No results have been recorded yet.*\n"
63+
return "\n".join(blocks)
64+
65+
66+
if __name__ == "__main__":
67+
Path(sys.argv[1]).write_text(render())

‎benchmarks/requirements.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
matplotlib
2+
numpy
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
{
2+
"date": "2026-11-07",
3+
"repeats": 5,
4+
"machine": {
5+
"cpu": "Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz",
6+
"cpu_ghz": 0.4,
7+
"os": "Linux",
8+
"fortran_compiler": "GNU Fortran (Ubuntu 15.2.0-16ubuntu1) 15.2.0",
9+
"fortran_flags": "-O3 -march=native",
10+
"fpm": "Version: 0.13.0, alpha",
11+
"python": "CPython 3.14.4",
12+
"matplotlib": "3.11.2",
13+
"numpy": "2.3.5"
14+
},
15+
"results": [
16+
{
17+
"benchmark": "Compile library",
18+
"variant": "fplotlib (fpm build, -O3)",
19+
"seconds": 21.074636
20+
},
21+
{
22+
"benchmark": "Compile simple program",
23+
"variant": "Fortran compile to binary",
24+
"seconds": 0.110779
25+
},
26+
{
27+
"benchmark": "Import simple script",
28+
"variant": "Python imports (matplotlib, numpy)",
29+
"seconds": 0.43922
30+
},
31+
{
32+
"benchmark": "Run simple -> png",
33+
"variant": "fplotlib",
34+
"seconds": 0.048328
35+
},
36+
{
37+
"benchmark": "Run simple -> png",
38+
"variant": "matplotlib (excl. imports)",
39+
"seconds": 0.074703
40+
},
41+
{
42+
"benchmark": "Run simple -> pdf",
43+
"variant": "fplotlib",
44+
"seconds": 0.002185
45+
},
46+
{
47+
"benchmark": "Run simple -> pdf",
48+
"variant": "matplotlib (excl. imports)",
49+
"seconds": 0.133638
50+
},
51+
{
52+
"benchmark": "Compile complex program",
53+
"variant": "Fortran compile to binary",
54+
"seconds": 0.11186
55+
},
56+
{
57+
"benchmark": "Import complex script",
58+
"variant": "Python imports (matplotlib, numpy)",
59+
"seconds": 0.425692
60+
},
61+
{
62+
"benchmark": "Run complex -> png",
63+
"variant": "fplotlib",
64+
"seconds": 0.069669
65+
},
66+
{
67+
"benchmark": "Run complex -> png",
68+
"variant": "matplotlib (excl. imports)",
69+
"seconds": 0.152285
70+
},
71+
{
72+
"benchmark": "Run complex -> pdf",
73+
"variant": "fplotlib",
74+
"seconds": 0.056001
75+
},
76+
{
77+
"benchmark": "Run complex -> pdf",
78+
"variant": "matplotlib (excl. imports)",
79+
"seconds": 0.226113
80+
},
81+
{
82+
"benchmark": "Compile animation program",
83+
"variant": "Fortran compile to binary",
84+
"seconds": 0.090391
85+
},
86+
{
87+
"benchmark": "Import animation script",
88+
"variant": "Python imports (matplotlib, numpy)",
89+
"seconds": 0.43272
90+
},
91+
{
92+
"benchmark": "Run animation -> gif",
93+
"variant": "fplotlib",
94+
"seconds": 0.966446
95+
},
96+
{
97+
"benchmark": "Run animation -> gif",
98+
"variant": "matplotlib (excl. imports)",
99+
"seconds": 4.471388
100+
}
101+
]
102+
}

0 commit comments

Comments
 (0)