|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +#include <format> |
| 5 | +#include <stdexcept> |
| 6 | + |
| 7 | +#include "spdlog/spdlog.h" |
| 8 | + |
| 9 | +#if defined(_WIN32) || defined(_WIN64) |
| 10 | +#include <windows.h> |
| 11 | +#else |
| 12 | +#include <sys/resource.h> |
| 13 | +#include <unistd.h> |
| 14 | +#endif |
| 15 | + |
| 16 | +namespace utils { |
| 17 | + |
| 18 | +/// @brief application process helpers |
| 19 | +struct Process { |
| 20 | + public: |
| 21 | + /// @brief Sets the current process to run with high priority. |
| 22 | + /// |
| 23 | + /// This function attempts to increase the execution priority of the current process. |
| 24 | + /// On Windows systems, it sets the process priority class to a higher level |
| 25 | + /// (e.g. `HIGH_PRIORITY_CLASS`). On Unix-like systems, it adjusts the process "nice" |
| 26 | + /// value. The function uses `utils::Process::set_process_priority()` to apply the |
| 27 | + /// change and logs the result. |
| 28 | + /// |
| 29 | + /// @throws std::runtime_error If the process priority cannot be changed successfully. |
| 30 | + static void set_high_priority() { |
| 31 | + int priority = 0; |
| 32 | +#if defined(_WIN32) || defined(_WIN64) |
| 33 | + priority = 1; // HIGH_PRIORITY_CLASS |
| 34 | +#else |
| 35 | + priority = -20; // Unix nice value |
| 36 | +#endif |
| 37 | + utils::Process::set_process_priority(priority); |
| 38 | + } |
| 39 | + |
| 40 | + private: |
| 41 | + /// @brief Set the priority of the current process. |
| 42 | + /// @param priority On Linux/macOS: nice value (-20 highest → +19 lowest) |
| 43 | + /// On Windows: 0=NORMAL, 1=HIGH, 2=REALTIME |
| 44 | + /// @throw std::runtime_error if priority cannot be set |
| 45 | + static void set_process_priority(int priority) { |
| 46 | +#if defined(_WIN32) || defined(_WIN64) |
| 47 | + DWORD win_prio; |
| 48 | + switch (priority) { |
| 49 | + case 0: |
| 50 | + win_prio = NORMAL_PRIORITY_CLASS; |
| 51 | + break; |
| 52 | + case 1: |
| 53 | + win_prio = HIGH_PRIORITY_CLASS; |
| 54 | + break; |
| 55 | + case 2: |
| 56 | + win_prio = REALTIME_PRIORITY_CLASS; |
| 57 | + break; |
| 58 | + default: |
| 59 | + win_prio = NORMAL_PRIORITY_CLASS; |
| 60 | + break; |
| 61 | + } |
| 62 | + if (!SetPriorityClass(GetCurrentProcess(), win_prio)) { |
| 63 | + throw std::runtime_error("failed to set windows process priority"); |
| 64 | + } |
| 65 | + |
| 66 | +#else |
| 67 | + int ret = setpriority(PRIO_PROCESS, 0, priority); |
| 68 | + if (ret != 0) { |
| 69 | + perror("setpriority"); |
| 70 | + throw std::runtime_error(std::format( |
| 71 | + "failed to set posix process priority. value [{}], ret [{}]", priority, ret)); |
| 72 | + } |
| 73 | +#endif |
| 74 | + } |
| 75 | +}; |
| 76 | + |
| 77 | +} // namespace utils |
0 commit comments