diff --git a/openmp.cpp b/openmp.cpp index 85e8dd4..f772ea3 100644 --- a/openmp.cpp +++ b/openmp.cpp @@ -7,6 +7,31 @@ #include #include +std::vector multiply(std::vector a, std::vector b, int n, bool isParallel) { + double start_time = omp_get_wtime(); + std::vector c(n*n, 0.); + #pragma omp parallel for collapse(3) if(isParallel) + for(int i = 0; i < n; ++i) + for(int j = 0; j < n; ++j) + for(int k = 0; k < n; ++k) + c[i*n + j] += a[i*n + k] * b[k*n + j]; + double run_time = omp_get_wtime() - start_time; + printf("Execution (%s): %fs\n", isParallel ? "parallel" : "sequential", run_time); + return c; +} + +bool isResultCorrect(std::vector a, std::vector b, std::vector c) { + for(int i = 0; i < n; ++i) { + for(int j = 0; j < n; ++j) { + double t = 0; + for(int k = 0; k < n; ++k) + t += a[i*n + k] * b[k*n + j]; + if (std::abs(t - c[i*n + j]) > 1e-16) return false; + } + } + return true; +} + //Matrix multiplication int main(int argc, char *argv[]) { @@ -14,26 +39,13 @@ int main(int argc, char *argv[]) std::vector a(n*n); std::vector b(n*n); - std::vector c(n*n, 0.); std::srand(std::time(0)); std::generate(a.begin(), a.end(), std::rand); std::generate(b.begin(), b.end(), std::rand); - for(int i = 0; i < n; ++i) - for(int j = 0; j < n; ++j) - for(int k = 0; k < n; ++k) - c[i*n + j] += a[i*n + k] * b[k*n + j]; - - // Test correctness - for(int i = 0; i < n; ++i) - for(int j = 0; j < n; ++j) { - double t = 0; - for(int k = 0; k < n; ++k) - t += a[i*n + k] * b[k*n + j]; - if (std::abs(t - c[i*n + j]) > 1e-16) return 1; - } - - return 0; + std::vector p = multiply(a, b, n, true); + std::vector s = multiply(a, b, n, false); + return (isResultCorrect(a, b, p) && isResultCorrect(a, b, s)) ? 0 : 1; }