On Thursday, 28 March 2024 at 11:50:38 UTC, rkompass wrote:
Turning back to this: Are there similarly simple libraries for
C, that allow for
parallel computation?
You can achieve parallelism in C using libraries such as OpenMP,
which provides a set of compiler directives and runtime library
routines for parallel programming.
Here’s an example of how you might modify the code to use OpenMP
for parallel processing:
```c
#include <stdio.h>
#include <time.h>
#include <omp.h>
#define ITERS 1000000000
#define STEPS 31
double leibniz(int i) {
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;
}
int main() {
double start_time = omp_get_wtime();
double result = 0.0;
#pragma omp parallel for reduction(+:result)
for (int s = ITERS; s >= 0; s -= STEPS) {
result += leibniz(s);
}
// Calculate the time taken
double time_taken = omp_get_wtime() - start_time;
printf("%.16f\n", result);
printf("%f (seconds)\n", time_taken);
return 0;
}
```
To compile this code with OpenMP support, you would use a command
like gcc -fopenmp your_program.c. This tells the GCC compiler to
enable OpenMP directives. The #pragma omp parallel for directive
tells the compiler to parallelize the loop, and the reduction
clause is used to safely accumulate the result variable across
multiple threads.
SDB@79