Why is this code slow?

kdevel kdevel at vogtner.de
Sun Mar 24 21:21:13 UTC 2024


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

Usually you do not translate mathematical expressions directly 
into code:

```
    n += pow(-1.0, i - 1.0) / (i * 2.0 - 1.0);
```

The term containing the `pow` invocation computes the alternating 
sequence -1, 1, -1, ..., which can be replaced by e.g.

```
    immutable int [2] sign = [-1, 1];
    n += sign [i & 1] / (i * 2.0 - 1.0);
```

This saves the expensive call to the pow function.


More information about the Digitalmars-d-learn mailing list