Loading...
Searching...
No Matches
parallel_algorithms.h
Go to the documentation of this file.
1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 Artificial Intelligence Techniques, S.L. and Roberto López González
3
4#pragma once
5#ifndef OPENNN_PARALLEL_ALGORITHMS_H_
6#define OPENNN_PARALLEL_ALGORITHMS_H_
7
9
10#if defined(OPENNN_HAS_PARALLEL_ALGORITHMS)
11#include <execution>
12#endif
13
14#if defined(_OPENMP)
15#include <omp.h>
16#endif
17
18namespace opennn
19{
20
21inline constexpr ptrdiff_t parallel_algorithm_min_size = 65536;
22
23inline bool use_parallel_algorithm(ptrdiff_t size) noexcept
24{
25 if (size < parallel_algorithm_min_size) return false;
26#if defined(_OPENMP)
27 if (omp_in_parallel()) return false;
28#endif
29 return true;
30}
31
32template<typename Iterator, typename Compare = less<>>
33void sort_parallel_if_large(Iterator first, Iterator last, Compare compare = {})
34{
35#if defined(OPENNN_HAS_PARALLEL_ALGORITHMS) && defined(__cpp_lib_parallel_algorithm)
36 if (use_parallel_algorithm(last - first))
37 sort(execution::par, first, last, compare);
38 else
39#endif
40 sort(first, last, compare);
41}
42
43template<typename Iterator, typename Compare = less<>>
44void stable_sort_parallel_if_large(Iterator first, Iterator last, Compare compare = {})
45{
46#if defined(OPENNN_HAS_PARALLEL_ALGORITHMS) && defined(__cpp_lib_parallel_algorithm)
47 if (use_parallel_algorithm(last - first))
48 stable_sort(execution::par, first, last, compare);
49 else
50#endif
51 stable_sort(first, last, compare);
52}
53
54template<typename Iterator, typename Compare = less<>>
55void nth_element_parallel_if_large(Iterator first, Iterator nth, Iterator last,
56 Compare compare = {})
57{
58#if defined(OPENNN_HAS_PARALLEL_ALGORITHMS) && defined(__cpp_lib_parallel_algorithm)
59 if (use_parallel_algorithm(last - first))
60 nth_element(execution::par, first, nth, last, compare);
61 else
62#endif
63 nth_element(first, nth, last, compare);
64}
65
66}
67
68#endif
Definition configuration.h:10
void stable_sort_parallel_if_large(Iterator first, Iterator last, Compare compare={})
Definition parallel_algorithms.h:44
bool use_parallel_algorithm(ptrdiff_t size) noexcept
Definition parallel_algorithms.h:23
void nth_element_parallel_if_large(Iterator first, Iterator nth, Iterator last, Compare compare={})
Definition parallel_algorithms.h:55
constexpr ptrdiff_t parallel_algorithm_min_size
Definition parallel_algorithms.h:21
void sort_parallel_if_large(Iterator first, Iterator last, Compare compare={})
Definition parallel_algorithms.h:33