Why is this code slow?

rkompass rkompass at gmx.de
Mon Mar 25 14:02:08 UTC 2024


On Sunday, 24 March 2024 at 23:02:19 UTC, Sergey wrote:
> On Sunday, 24 March 2024 at 22:16:06 UTC, rkompass wrote:
>> Are there some simple switches / settings to get a smaller 
>> binary?
>
> 1) If possible you can use "betterC" - to disable runtime
> 2) otherwise
> ```bash
> --release --O3 --flto=full -fvisibility=hidden 
> -defaultlib=phobos2-ldc-lto,druntime-ldc-lto -L=-dead_strip 
> -L=-x -L=-S -L=-lz
> ```

Thank you. I succeeded with `gdc -Wall -O2 -frelease 
-shared-libphobos`

A little remark:
The approximation to pi is slow, but oscillates up and down much 
more than its average. So doing the average of 2 steps gives many 
more precise digits. We can simulate this by doing a last step 
with half the size:

```d
double leibniz(int it) {
   double n = 1.0;
   for (int i = 1; i < it; i++)
     n += ((i%2) ? -1.0 : 1.0) / (i * 2.0 + 1.0);
   n += 0.5*((it%2) ? -1.0 : 1.0) / (it * 2.0 + 1.0);
   return n * 4.0;
}
```
Of course you may also combine the up(+) and down(-) step to one:

1/i - 1/(i+2) = 2/(i*(i+2))

```d
double leibniz(int iter) {
   double n = 0.0;
   for (int i = 1; i < iter; i+=4)
     n += 2.0 / (i * (i+2.0));
   return n * 4.0;
}
```
or even combine both approaches. But of, course mathematically 
much more is possible. This was not about approximating pi as 
fast as possible...

The above first approach still works with the original speed, 
only makes the result a little bit nicer.


More information about the Digitalmars-d-learn mailing list