Why is this code slow?

rkompass rkompass at gmx.de
Sun Mar 24 22:16:06 UTC 2024


> 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.

I used the loop:
```d
	for (int i = 1; i < iter; i++)
		n += ((i%2) ? -1.0 : 1.0) / (i * 2.0 + 1.0);
```
in both C and D, with gcc and gdc and got average execution times:

--- C -----
original:  ....   loop replacement: ....      -O2:
0.009989   ....        0.003198     ...........     0.001335

--- D -----
original:  ....    loop replacement: ....     -O2:
0.230346   ....       0.003083       ...........   0.001309

almost no difference.

But the D binary is much larger on my Linux:
  4600920 bytes instead of 15504 bytes for the C version.

Are there some simple switches / settings to get a smaller binary?


More information about the Digitalmars-d-learn mailing list