1 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2    Copyright (c) 2014-2021 The plumed team
3    (see the PEOPLE file at the root of the distribution for a list of names)
4 
5    See http://www.plumed.org for more information.
6 
7    This file is part of plumed, version 2.
8 
9    plumed is free software: you can redistribute it and/or modify
10    it under the terms of the GNU Lesser General Public License as published by
11    the Free Software Foundation, either version 3 of the License, or
12    (at your option) any later version.
13 
14    plumed is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU Lesser General Public License for more details.
18 
19    You should have received a copy of the GNU Lesser General Public License
20    along with plumed.  If not, see <http://www.gnu.org/licenses/>.
21 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
22 #ifndef __PLUMED_tools_OpenMP_h
23 #define __PLUMED_tools_OpenMP_h
24 
25 #include <vector>
26 
27 namespace PLMD {
28 
29 class OpenMP {
30 
31 public:
32 
33 /// Set number of threads that can be used by openMP
34   static void setNumThreads(const unsigned nt);
35 
36 /// Get number of threads that can be used by openMP
37   static unsigned getNumThreads();
38 
39 /// Returns a unique thread identification number within the current team
40   static unsigned getThreadNum();
41 
42 /// get cacheline size
43   static unsigned getCachelineSize();
44 
45 /// Get a reasonable number of threads so as to access to an array of size s located at x
46   template<typename T>
47   static unsigned getGoodNumThreads(const T*x,unsigned s);
48 
49 /// Get a reasonable number of threads so as to access to vector v;
50   template<typename T>
51   static unsigned getGoodNumThreads(const std::vector<T> & v);
52 
53 };
54 
55 template<typename T>
getGoodNumThreads(const T * x,unsigned n)56 unsigned OpenMP::getGoodNumThreads(const T*x,unsigned n) {
57   unsigned long p=(unsigned long) x;
58   (void) p; // this is not to have warnings. notice that the pointer location is not used actually.
59 // a factor two is necessary since there is no guarantee that x is aligned
60 // to cache line boundary
61   unsigned m=n*sizeof(T)/(2*getCachelineSize());
62   unsigned numThreads=getNumThreads();
63   if(m>=numThreads) m=numThreads;
64   else m=1;
65   return m;
66 }
67 
68 
69 template<typename T>
getGoodNumThreads(const std::vector<T> & v)70 unsigned OpenMP::getGoodNumThreads(const std::vector<T> & v) {
71   if(v.size()==0) return 1;
72   else return getGoodNumThreads(&v[0],v.size());
73 }
74 
75 
76 }
77 
78 #endif
79