On Sunday, 24 March 2024 at 19:31:19 UTC, Csaba wrote:
I know that benchmarks are always controversial and depend on a
lot of factors. So far, I read that D performs very well in
benchmarks, as well, if not better, as C.
I wrote a little program that approximates PI using the Leibniz
formula. I implemented the same thing in C, D and Python, all
of them execute 1,000,000 iterations 20 times and display the
average time elapsed.
Here are the results:
C: 0.04s
Python: 0.33s
D: 0.73s
What the hell? D slower than Python? This cannot be real. I am
sure I am making a mistake here. I'm sharing all 3 programs
here:
C: https://pastebin.com/s7e2HFyL
D: https://pastebin.com/fuURdupc
Python: https://pastebin.com/zcXAkSEf
As you can see the function that does the job is exactly the
same in C and D.
Here are the compile/run commands used:
C: `gcc leibniz.c -lm -oleibc`
D: `gdc leibniz.d -frelease -oleibd`
Python: `python3 leibniz.py`
PS. my CPU is AMD A8-5500B and my OS is Ubuntu Linux, if that
matters.
As others suggested, pow is the problem. I noticed that the C
versions are often much faster than their D counterparts. (And I
don't view that as a problem, since both are built into the
language - my only thought is that the D version should call the
C version).
Changing
```
import std.math:pow;
```
to
```
import core.stdc.math: pow;
```
and leaving everything unchanged, I get
C: Avg execution time: 0.007918
D (original): Avg execution time: 0.102612
D (using core.stdc.math): Avg execution time: 0.008134
So more or less the exact same numbers if you use core.stdc.math.