From 346de6a0883e9d21b6e1db882bf91f09f068573d Mon Sep 17 00:00:00 2001 From: robtor Date: Tue, 19 Dec 2023 12:43:47 +0100 Subject: [PATCH] Add OpenMP task --- CMakeLists.txt | 3 ++- task5/CMakeLists.txt | 22 +++++++++++++++++++ task5/src/main.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 task5/CMakeLists.txt create mode 100644 task5/src/main.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 536554d..9457204 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,4 +28,5 @@ add_subdirectory(third-party/fmt) add_subdirectory(task1) add_subdirectory(task2) add_subdirectory(task3) -add_subdirectory(task4) \ No newline at end of file +add_subdirectory(task4) +add_subdirectory(task5) \ No newline at end of file diff --git a/task5/CMakeLists.txt b/task5/CMakeLists.txt new file mode 100644 index 0000000..a85de93 --- /dev/null +++ b/task5/CMakeLists.txt @@ -0,0 +1,22 @@ +find_package(Qt6 COMPONENTS Core REQUIRED) +find_package(OpenMP) + +if (OPENMP_FOUND) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}") +endif () + +add_executable(task5-chpt4ex4) + +target_include_directories(task5-chpt4ex4 PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include) + +target_sources(task5-chpt4ex4 PRIVATE + src/main.cpp +) + + +target_link_libraries(task4-monitor PRIVATE + Qt6::Core + OpenMP::OpenMP_CXX) diff --git a/task5/src/main.cpp b/task5/src/main.cpp new file mode 100644 index 0000000..9fed687 --- /dev/null +++ b/task5/src/main.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +#include + +class MidsumException : std::exception { + const char *what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW override { + return "Invalid call to midsum function"; + } +}; + +auto midsum(std::function fun, double x1, double x2) -> double { + if (x2 <= x1) { + throw MidsumException(); + } + auto dx = x2 - x1; + return fun((x1 + (dx / 2))) * dx; +} + +auto csin(double arg) -> double { + return std::sin(arg) + 1; +} + +auto main(int argc, char **argv) -> int { + double midsum_val; + double from = 0; + double to = 2 * std::numbers::pi; + int slices = 20; + double step = 1.0 * (to - from) / slices; + + std::cout << "Num slices: " << slices << " Step size: " << step << std::endl; + +#pragma omp parallel + { + #pragma omp for + + for (int i = 0; i < slices; i++) { + std::cout << "Calculating step: " << i << " from " << i * step << " to " << (i + 1) * step << std::endl; + midsum_val += midsum(csin, (i * step), ((i + 1) * step)); + } + + } + + std::cout << midsum_val << + std::endl; + + + return 0; +} \ No newline at end of file