|
1 | 1 | #ifndef CP_ALGO_UTIL_NEW_BIG_HPP |
2 | 2 | #define CP_ALGO_UTIL_NEW_BIG_HPP |
3 | | -#include <sys/mman.h> |
| 3 | +#include <cstddef> |
| 4 | + |
| 5 | +// Single macro to detect POSIX platforms (Linux, Unix, macOS) |
| 6 | +#if defined(__linux__) || defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) |
| 7 | +# define CP_ALGO_USE_MMAP 1 |
| 8 | +# include <sys/mman.h> |
| 9 | +#else |
| 10 | +# define CP_ALGO_USE_MMAP 0 |
| 11 | +#endif |
| 12 | + |
4 | 13 | namespace cp_algo { |
5 | 14 | template<typename T> |
6 | | - auto new_big(size_t len) { |
7 | | - auto raw = mmap(nullptr, len * sizeof(T), |
8 | | - PROT_READ | PROT_WRITE, |
9 | | - MAP_PRIVATE | MAP_ANONYMOUS, |
10 | | - -1, 0); |
| 15 | + T* new_big(std::size_t len) { |
| 16 | +#if CP_ALGO_USE_MMAP |
| 17 | + void* raw = mmap(nullptr, len * sizeof(T), |
| 18 | + PROT_READ | PROT_WRITE, |
| 19 | + MAP_PRIVATE | MAP_ANONYMOUS, |
| 20 | + -1, 0); |
| 21 | + // Advise the kernel for huge pages and pre-populate writes |
11 | 22 | madvise(raw, len * sizeof(T), MADV_HUGEPAGE); |
12 | 23 | madvise(raw, len * sizeof(T), MADV_POPULATE_WRITE); |
13 | 24 | return static_cast<T*>(raw); |
| 25 | +#else |
| 26 | + // Fallback allocation for non-POSIX platforms |
| 27 | + return new T[len]; |
| 28 | +#endif |
14 | 29 | } |
15 | 30 | template<typename T> |
16 | | - void delete_big(T* ptr, size_t len) { |
| 31 | + void delete_big(T* ptr, [[maybe_unused]] std::size_t len) { |
| 32 | +#if CP_ALGO_USE_MMAP |
17 | 33 | munmap(ptr, len * sizeof(T)); |
| 34 | +#else |
| 35 | + // Match allocation with delete[] on non-POSIX platforms |
| 36 | + delete[] ptr; |
| 37 | +#endif |
18 | 38 | } |
19 | 39 | } |
20 | 40 | #endif // CP_ALGO_UTIL_NEW_BIG_HPP |
0 commit comments