FMS  2025.03
Flexible Modeling System
mpp_memuse.c
1 /***********************************************************************
2  * GNU Lesser General Public License
3  *
4  * This file is part of the GFDL Flexible Modeling System (FMS).
5  *
6  * FMS is free software: you can redistribute it and/or modify it under
7  * the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or (at
9  * your option) any later version.
10  *
11  * FMS is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FMS. If not, see <http://www.gnu.org/licenses/>.
18  **********************************************************************/
19 
20 /**
21  * \Author David Robert Nadeau
22  * Site: http://NadeauSoftware.com/
23  * License: Creative Commons Attribution 3.0 Unported License
24  * http://creativecommons.org/licenses/by/3.0/deed.en_US
25  */
26 
27 /* Include headers common for Unix and Unix-like OSs. __unix__ is defined on Linux OSs */
28 #if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
29 #include <unistd.h>
30 #include <sys/resource.h>
31 
32 /* Include specific headers for specific OS types */
33 #if defined(__APPLE__) && defined(__MACH__)
34 #include <mach/mach.h>
35 
36 #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
37 #include <stdio.h>
38 /* #endif for specific headers checks */
39 #endif
40 
41 #else
42 /* Not a Unix-like OS. Not supported */
43 #error "Cannot define getPeakRSS( ) for an unknown OS."
44 #endif
45 
46 /**
47  * Returns the peak (maximum so far) resident set size (physical
48  * memory use) measured in bytes, or zero if the value cannot be
49  * determined on this OS.
50  */
51 size_t getpeakrss( )
52 {
53 #if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
54  /* BSD, Linux, and OSX -------------------------------------- */
55  struct rusage rusage;
56  getrusage( RUSAGE_SELF, &rusage );
57 #if defined(__APPLE__) && defined(__MACH__)
58  return (size_t)rusage.ru_maxrss;
59 #else
60  return (size_t)(rusage.ru_maxrss * 1024L);
61 #endif
62 
63 #else
64  /* Unknown OS ----------------------------------------------- */
65  return (size_t)0L; /* Unsupported. */
66 #endif
67 }