AUTH's THMMY "Parallel and distributed systems" course assignments.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

357 行
13 KiB

  1. /**
  2. * \file
  3. * \brief Utilities header
  4. *
  5. * \author
  6. * Christos Choutouridis AEM:8997
  7. * <cchoutou@ece.auth.gr>
  8. */
  9. #ifndef UTILS_HPP_
  10. #define UTILS_HPP_
  11. #include <vector>
  12. #include <iostream>
  13. #include <chrono>
  14. #include <unistd.h>
  15. #include <mpi.h>
  16. #include "config.h"
  17. /*
  18. * MPI_<type> dispatcher mechanism
  19. */
  20. template <typename T> struct MPI_TypeMapper { };
  21. template <> struct MPI_TypeMapper<char> { static MPI_Datatype getType() { return MPI_CHAR; } };
  22. template <> struct MPI_TypeMapper<short> { static MPI_Datatype getType() { return MPI_SHORT; } };
  23. template <> struct MPI_TypeMapper<int> { static MPI_Datatype getType() { return MPI_INT; } };
  24. template <> struct MPI_TypeMapper<long> { static MPI_Datatype getType() { return MPI_LONG; } };
  25. template <> struct MPI_TypeMapper<long long> { static MPI_Datatype getType() { return MPI_LONG_LONG; } };
  26. template <> struct MPI_TypeMapper<unsigned char> { static MPI_Datatype getType() { return MPI_UNSIGNED_CHAR; } };
  27. template <> struct MPI_TypeMapper<unsigned short>{ static MPI_Datatype getType() { return MPI_UNSIGNED_SHORT; } };
  28. template <> struct MPI_TypeMapper<unsigned int> { static MPI_Datatype getType() { return MPI_UNSIGNED; } };
  29. template <> struct MPI_TypeMapper<unsigned long> { static MPI_Datatype getType() { return MPI_UNSIGNED_LONG; } };
  30. template <> struct MPI_TypeMapper<unsigned long long> { static MPI_Datatype getType() { return MPI_UNSIGNED_LONG_LONG; } };
  31. template <> struct MPI_TypeMapper<float> { static MPI_Datatype getType() { return MPI_FLOAT; } };
  32. template <> struct MPI_TypeMapper<double> { static MPI_Datatype getType() { return MPI_DOUBLE; } };
  33. /*!
  34. * MPI wrapper type to provide MPI functionality and RAII to MPI as a resource
  35. *
  36. * @tparam TID The MPI type for process id [default: int]
  37. */
  38. template<typename TID = int>
  39. struct MPI_t {
  40. using ID_t = TID; // Export TID type (currently int defined by the standard)
  41. /*!
  42. * Initializes the MPI environment, must called from each process
  43. *
  44. * @param argc [int*] POINTER to main's argc argument
  45. * @param argv [car***] POINTER to main's argv argument
  46. */
  47. void init(int *argc, char ***argv) {
  48. // Initialize the MPI environment
  49. int err;
  50. if ((err = MPI_Init(argc, argv)) != MPI_SUCCESS)
  51. mpi_throw(err, "(MPI) MPI_Init() - ");
  52. initialized_ = true;
  53. // Get the number of processes
  54. int size_value, rank_value;
  55. if ((err = MPI_Comm_size(MPI_COMM_WORLD, &size_value)) != MPI_SUCCESS)
  56. mpi_throw(err, "(MPI) MPI_Comm_size() - ");
  57. if ((err = MPI_Comm_rank(MPI_COMM_WORLD, &rank_value)) != MPI_SUCCESS)
  58. mpi_throw(err, "(MPI) MPI_Comm_rank() - ");
  59. size_ = static_cast<ID_t>(size_value);
  60. rank_ = static_cast<ID_t>(rank_value);
  61. // Get the name of the processor
  62. char processor_name[MPI_MAX_PROCESSOR_NAME];
  63. int name_len;
  64. if ((err = MPI_Get_processor_name(processor_name, &name_len)) != MPI_SUCCESS)
  65. mpi_throw(err, "(MPI) MPI_Get_processor_name() - ");
  66. name_ = std::string (processor_name, name_len);
  67. }
  68. /*!
  69. * Exchange data with partner as part of the sorting network of both bubbletonic or bitonic
  70. * sorting algorithms.
  71. *
  72. * This function matches a transmit and a receive in order for fully exchanged data between
  73. * current node and partner.
  74. *
  75. * @tparam T The inner valur type used in buffer
  76. *
  77. * @param partner [mpi_id_t] The partner for the exchange
  78. * @param send_data [std::vector<T>] Reference to local data to send
  79. * @param recv_data [std::vector<T>] Reference to buffer to receive data from partner
  80. * @param tag [int] The tag to use for the MPI communication
  81. */
  82. template<typename T>
  83. void exchange(ID_t partner, const std::vector<T>& send_data, std::vector<T>& recv_data, int tag) {
  84. using namespace std::string_literals;
  85. MPI_Datatype datatype = MPI_TypeMapper<T>::getType();
  86. int send_count = static_cast<int>(send_data.size());
  87. MPI_Status status;
  88. int err;
  89. if ((err = MPI_Sendrecv(
  90. send_data.data(), send_count, datatype, partner, tag,
  91. recv_data.data(), send_count, datatype, partner, tag,
  92. MPI_COMM_WORLD, &status
  93. )) != MPI_SUCCESS)
  94. mpi_throw(err, "(MPI) MPI_Sendrecv() - ");
  95. }
  96. // Accessors
  97. [[nodiscard]] ID_t rank() const noexcept { return rank_; }
  98. [[nodiscard]] ID_t size() const noexcept { return size_; }
  99. [[nodiscard]] const std::string& name() const noexcept { return name_; }
  100. /*!
  101. * Finalized the MPI
  102. */
  103. void finalize() {
  104. // Finalize the MPI environment
  105. initialized_ = false;
  106. MPI_Finalize();
  107. }
  108. //! RAII MPI finalization
  109. ~MPI_t() {
  110. // Finalize the MPI environment even on unexpected errors
  111. if (initialized_)
  112. MPI_Finalize();
  113. }
  114. // Local functionality
  115. private:
  116. /*!
  117. * Throw exception helper. It bundles the prefix with the MPI error string retrieved by
  118. * MPI API.
  119. *
  120. * @param err The MPI error code
  121. * @param prefixMsg The prefix text for the exception error message
  122. */
  123. void mpi_throw(int err, const char* prefixMsg) {
  124. char err_msg[MPI_MAX_ERROR_STRING];
  125. int msg_len;
  126. MPI_Error_string(err, err_msg, &msg_len);
  127. throw std::runtime_error(prefixMsg + std::string (err_msg) + '\n');
  128. }
  129. #if !defined TESTING
  130. private:
  131. #else
  132. public:
  133. #endif
  134. ID_t rank_{}; //!< MPI rank of the process
  135. ID_t size_{}; //!< MPI total size of the execution
  136. std::string name_{}; //!< The name of the local machine
  137. bool initialized_{}; //!< RAII helper flag
  138. };
  139. /*
  140. * Exported data types
  141. */
  142. extern MPI_t<> mpi;
  143. using mpi_id_t = MPI_t<>::ID_t;
  144. /*!
  145. * A std::vector wrapper with 2 vectors, an active and a shadow. This type exposes the standard vector
  146. * functionality of the active vector. The shadow can be used when we need to use the vector as mutable
  147. * data in algorithms that can not support "in-place" editing (like elbow-sort for example)
  148. *
  149. * @tparam Value_t the inner data type of the vectors
  150. */
  151. template <typename Value_t>
  152. struct ShadowedVec_t {
  153. // STL requirements
  154. using value_type = Value_t;
  155. using iterator = typename std::vector<Value_t>::iterator;
  156. using const_iterator = typename std::vector<Value_t>::const_iterator;
  157. using size_type = typename std::vector<Value_t>::size_type;
  158. // Default constructor
  159. ShadowedVec_t() = default;
  160. // Constructor from an std::vector
  161. explicit ShadowedVec_t(const std::vector<Value_t>& vec)
  162. : North(vec), South(), active(north) {
  163. South.resize(North.size());
  164. }
  165. explicit ShadowedVec_t(std::vector<Value_t>&& vec)
  166. : North(std::move(vec)), South(), active(north) {
  167. South.resize(North.size());
  168. }
  169. // Copy assignment operator
  170. ShadowedVec_t& operator=(const ShadowedVec_t& other) {
  171. if (this != &other) { // Avoid self-assignment
  172. North = other.North;
  173. South = other.South;
  174. active = other.active;
  175. }
  176. return *this;
  177. }
  178. // Move assignment operator
  179. ShadowedVec_t& operator=(ShadowedVec_t&& other) noexcept {
  180. if (this != &other) { // Avoid self-assignment
  181. North = std::move(other.North);
  182. South = std::move(other.South);
  183. active = other.active;
  184. // There is no need to zero out other since it is valid but in a non-defined state
  185. }
  186. return *this;
  187. }
  188. // Type accessors
  189. const std::vector<Value_t>& getNorth() const { return North; }
  190. const std::vector<Value_t>& getSouth() const { return South; }
  191. std::vector<Value_t>& getActive() { return (active == north) ? North : South; }
  192. std::vector<Value_t>& getShadow() { return (active == north) ? South : North; }
  193. const std::vector<Value_t>& getActive() const { return (active == north) ? North : South; }
  194. const std::vector<Value_t>& getShadow() const { return (active == north) ? South : North; }
  195. // Switching vectors
  196. void switch_active() { active = (active == north) ? south : north; }
  197. // Dispatch to active vector functionality
  198. Value_t& operator[](size_type index) { return getActive()[index]; }
  199. const Value_t& operator[](size_type index) const { return getActive()[index]; }
  200. Value_t& at(size_type index) { return getActive().at(index); }
  201. const Value_t& at(size_type index) const { return getActive().at(index); }
  202. void push_back(const Value_t& value) { getActive().push_back(value); }
  203. void push_back(Value_t&& value) { getActive().push_back(std::move(value)); }
  204. void pop_back() { getActive().pop_back(); }
  205. Value_t& front() { return getActive().front(); }
  206. Value_t& back() { return getActive().back(); }
  207. const Value_t& front() const { return getActive().front(); }
  208. const Value_t& back() const { return getActive().back(); }
  209. iterator begin() { return getActive().begin(); }
  210. const_iterator begin() const { return getActive().begin(); }
  211. iterator end() { return getActive().end(); }
  212. const_iterator end() const { return getActive().end(); }
  213. size_type size() const { return getActive().size(); }
  214. void resize(size_t new_size) {
  215. North.resize(new_size);
  216. South.resize(new_size);
  217. }
  218. void reserve(size_t new_capacity) {
  219. North.reserve(new_capacity);
  220. South.reserve(new_capacity);
  221. }
  222. [[nodiscard]] size_t capacity() const { return getActive().capacity(); }
  223. [[nodiscard]] bool empty() const { return getActive().empty(); }
  224. void clear() { getActive().clear(); }
  225. void swap(std::vector<Value_t>& other) { getActive().swap(other); }
  226. // Comparisons
  227. bool operator== (const ShadowedVec_t& other) { return getActive() == other.getActive(); }
  228. bool operator!= (const ShadowedVec_t& other) { return getActive() != other.getActive(); }
  229. bool operator== (const std::vector<value_type>& other) { return getActive() == other; }
  230. bool operator!= (const std::vector<value_type>& other) { return getActive() != other; }
  231. private:
  232. std::vector<Value_t> North{}; //!< Actual buffer to be used either as active or shadow
  233. std::vector<Value_t> South{}; //!< Actual buffer to be used either as active or shadow
  234. enum {
  235. north, south
  236. } active{north}; //!< Flag to select between North and South buffer
  237. };
  238. using distBuffer_t = ShadowedVec_t<distValue_t>;
  239. extern distBuffer_t Data;
  240. /*!
  241. * A Logger for entire program.
  242. */
  243. struct Log {
  244. struct Endl {} endl; //!< a tag object to to use it as a new line request.
  245. //! We provide logging via << operator
  246. template<typename T>
  247. Log &operator<<(T &&t) {
  248. if (session.verbose) {
  249. if (line_) {
  250. std::cout << "[Log]: " << t;
  251. line_ = false;
  252. } else
  253. std::cout << t;
  254. }
  255. return *this;
  256. }
  257. // overload for special end line handling
  258. Log &operator<<(Endl e) {
  259. (void) e;
  260. if (session.verbose) {
  261. std::cout << '\n';
  262. line_ = true;
  263. }
  264. return *this;
  265. }
  266. private:
  267. bool line_{true};
  268. };
  269. extern Log logger;
  270. /*!
  271. * A small timing utility based on chrono.
  272. */
  273. struct Timing {
  274. using Tpoint = std::chrono::steady_clock::time_point;
  275. using microseconds = std::chrono::microseconds;
  276. using milliseconds = std::chrono::milliseconds;
  277. using seconds = std::chrono::seconds;
  278. //! tool to mark the starting point
  279. Tpoint start() noexcept { return start_ = std::chrono::steady_clock::now(); }
  280. //! tool to mark the ending point
  281. Tpoint stop() noexcept { return stop_ = std::chrono::steady_clock::now(); }
  282. auto dt() noexcept {
  283. return std::chrono::duration_cast<std::chrono::microseconds>(stop_ - start_).count();
  284. }
  285. //! tool to print the time interval
  286. void print_dt(const char *what) noexcept {
  287. if (session.timing) {
  288. auto t = stop_ - start_;
  289. if (std::chrono::duration_cast<microseconds>(t).count() < 10000)
  290. std::cout << "[Timing]: " << what << ": "
  291. << std::to_string(std::chrono::duration_cast<microseconds>(t).count()) << " [usec]\n";
  292. else if (std::chrono::duration_cast<milliseconds>(t).count() < 10000)
  293. std::cout << "[Timing]: " << what << ": "
  294. << std::to_string(std::chrono::duration_cast<milliseconds>(t).count()) << " [msec]\n";
  295. else
  296. std::cout << "[Timing]: " << what << ": "
  297. << std::to_string(std::chrono::duration_cast<seconds>(t).count()) << " [sec]\n";
  298. }
  299. }
  300. private:
  301. Tpoint start_;
  302. Tpoint stop_;
  303. };
  304. #endif /* UTILS_HPP_ */