Skip to content

Instantly share code, notes, and snippets.

@afarah1
Last active July 23, 2021 03:00
Show Gist options
  • Save afarah1/21677133c4011d8cd289eb3239340230 to your computer and use it in GitHub Desktop.
Save afarah1/21677133c4011d8cd289eb3239340230 to your computer and use it in GitHub Desktop.
Simple puzzle
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#define N 4
static bool
double_equal(double a, double b, double epsilon)
{
return fabs(a - b) < epsilon;
}
static void
init_arrays(double *arr1, double *arr2)
{
for (size_t i = 0; i < N; i++) {
arr1[i] = 0.5;
arr2[i] = 1.1;
}
}
static double
do_seq(double start, double *in1, double *in2)
{
double ans = start;
for (size_t i = 0; i < N; i++)
ans += in1[i] * in2[i];
return ans;
}
static double
do_par(double start, double *in1, double *in2)
{
double ans = start;
#pragma omp parallel for reduction(+:ans) schedule(static, 2) num_threads(2)
for (size_t i = 0; i < N; i++)
ans += in1[i] * in2[i];
return ans;
}
static void
test_parallel(void)
{
double arr1[N], arr2[N];
init_arrays(arr1, arr2);
assert(double_equal(
do_seq(10, arr1, arr2),
do_par(10, arr1, arr2),
1e-15
));
}
int
main()
{
test_parallel();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment