Why is this code slow?

rkompass rkompass at gmx.de
Thu Mar 28 11:50:38 UTC 2024


On Thursday, 28 March 2024 at 01:09:34 UTC, Salih Dincer wrote:
> Good thing you're digressing; I am 45 years old and I still 
> cannot say that I am finished as a student! For me this is 
> version 4 and it looks like we don't need a 3rd variable other 
> than the function parameter and return value:
>

So we go with another digression. I discovered parallel, also 
avoided the extra variable, as suggested by Salih:

```d
import std.range;
import std.parallelism;
import core.stdc.stdio: printf;
import std.datetime.stopwatch;

enum ITERS = 1_000_000_000;
enum STEPS = 31; // 5 is fine, even numbers (e.g. 10) may give 
bad precision (for math reason ???)

pure double leibniz(int i) {  // sum up the small values first
	double r = (i == ITERS) ? 0.5 * ((i%2) ? -1.0 : 1.0) / (i * 2.0 
+ 1.0) : 0.0;
	for (--i; i >= 0; i-= STEPS)
		r += ((i%2) ? -1.0 : 1.0) / (i * 2.0 + 1.0);
	return r * 4.0;
}

void main() {
	auto start = iota(ITERS, ITERS-STEPS, -1).array;
	auto sw = StopWatch(AutoStart.yes);
	double result = 0.0;
	foreach(s; start.parallel)
		result += leibniz(s);
	double total_time = sw.peek.total!"nsecs";
     printf("%.16f\n", result);
     printf("Execution time: %f\n", total_time / 1e9);
}
```
gives:
```
3.1415926535897931
Execution time: 0.211667
```
My laptop has 6 cores and obviously 5 are used in parallel by 
this.

The original question related to a comparison between C, D and 
Python.
Turning back to this: Are there similarly simple libraries for C, 
that allow for
parallel computation?



More information about the Digitalmars-d-learn mailing list