Debian Codegraph @

src/thirdparty/PoissonRecon/MyMiscellany.h

raw
1 /*
2 Copyright (c) 2017, Michael Kazhdan
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8 Redistributions of source code must retain the above copyright notice, this list of
9 conditions and the following disclaimer. Redistributions in binary form must reproduce
10 the above copyright notice, this list of conditions and the following disclaimer
11 in the documentation and/or other materials provided with the distribution.
12
13 Neither the name of the Johns Hopkins University nor the names of its contributors
14 may be used to endorse or promote products derived from this software without specific
15 prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
18 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
20 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
22 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 DAMAGE.
27 */
28 #ifndef MY_MISCELLANY_INCLUDED
29 #define MY_MISCELLANY_INCLUDED
30
31 #include <iostream>
32 #include <sstream>
33 #include <filesystem>
34 #include <string.h>
35 #include <sys/timeb.h>
36 #include <cstdio>
37 #include <ctime>
38 #include <chrono>
39 #if defined( _WIN32 ) || defined( _WIN64 )
40 #include <io.h>
41 #include <Windows.h>
42 #include <Psapi.h>
43 #else // !_WIN32 && !_WIN64
44 #include <unistd.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #endif // _WIN32 || _WIN64
48 #include <memory>
49 #if defined(_WIN32) || defined( _WIN64 )
50 #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
51 #if defined(__APPLE__) && defined(__MACH__)
52 #include <mach/mach.h>
53 #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
54 #include <fcntl.h>
55 #include <procfs.h>
56 #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
57 #include <stdio.h>
58 #endif
59
60 #else
61 #error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
62 #endif
63 #include "Array.h"
64 #include "MyAtomic.h"
65 #include "MultiThreading.h"
66
67 namespace PoissonRecon
68 {
69 ////////////////////////////
70 // Formatted float output //
71 ////////////////////////////
72 struct StreamFloatPrecision
73 {
74 StreamFloatPrecision( std::ostream &str , unsigned int precision , bool scientific=false ) : _str(str)
75 {
76 _defaultPrecision = (int)_str.precision();
77 _str.precision( precision );
78 if( scientific ) _str << std::scientific;
79 else _str << std::fixed;
80 }
81 ~StreamFloatPrecision( void )
82 {
83 _str << std::defaultfloat;
84 _str.precision( _defaultPrecision );
85 }
86 protected:
87 int _defaultPrecision;
88 std::ostream &_str;
89 };
90
91 ////////////////
92 // Time Stuff //
93 ////////////////
94 inline double Time( void )
95 {
96 #ifdef WIN32
97 struct _timeb t;
98 _ftime( &t );
99 return double( t.time ) + double( t.millitm ) / 1000.0;
100 #else // WIN32
101 struct timeval t;
102 gettimeofday( &t , NULL );
103 return t.tv_sec + double( t.tv_usec ) / 1000000;
104 #endif // WIN32
105 }
106
107 struct Timer
108 {
109 Timer( void ){ _startCPUClock = std::clock() , _startWallClock = std::chrono::system_clock::now(); }
110 double cpuTime( void ) const{ return (std::clock() - _startCPUClock) / (double)CLOCKS_PER_SEC; };
111 double wallTime( void ) const{ std::chrono::duration<double> diff = (std::chrono::system_clock::now() - _startWallClock) ; return diff.count(); }
112 std::string operator()( bool showCpuTime , unsigned int precision=1 ) const
113 {
114 std::stringstream ss;
115 StreamFloatPrecision sfp( ss , precision );
116 ss << wallTime() << " (s)";
117 if( showCpuTime ) ss << " / " << cpuTime() << " (s)";
118 return ss.str();
119 }
120 friend std::ostream &operator << ( std::ostream &os , const Timer &timer ){ return os << timer(false); }
121 protected:
122 std::clock_t _startCPUClock;
123 std::chrono::time_point< std::chrono::system_clock > _startWallClock;
124 };
125
126 ///////////////
127 // I/O Stuff //
128 ///////////////
129 #if defined( _WIN32 ) || defined( _WIN64 )
130 const char FileSeparator = '\\';
131 #else // !_WIN
132 const char FileSeparator = '/';
133 #endif // _WIN
134
135 #ifndef SetTempDirectory
136 #if defined( _WIN32 ) || defined( _WIN64 )
137 #define SetTempDirectory( tempDir , sz ) GetTempPath( (sz) , (tempDir) )
138 #else // !_WIN32 && !_WIN64
139 #define SetTempDirectory( tempDir , sz ) if( std::getenv( "TMPDIR" ) ) strcpy( tempDir , std::getenv( "TMPDIR" ) );
140 #endif // _WIN32 || _WIN64
141 #endif // !SetTempDirectory
142
143 #if defined( _WIN32 ) || defined( _WIN64 )
144 inline void FSync( FILE *fp )
145 {
146 // FlushFileBuffers( (HANDLE)_fileno( fp ) );
147 _commit( _fileno( fp ) );
148 }
149 #else // !_WIN32 && !_WIN64
150 inline void FSync( FILE *fp )
151 {
152 fsync( fileno( fp ) );
153 }
154 #endif // _WIN32 || _WIN64
155
156 //////////////////
157 // Memory Stuff //
158 //////////////////
159 size_t getPeakRSS( void );
160 size_t getCurrentRSS( void );
161
162 struct Profiler
163 {
164 Profiler( unsigned int ms=0 )
165 {
166 _t = Time();
167 _currentPeak = 0;
168 _terminate = false;
169 if( ms )
170 {
171 _thread = std::thread( &Profiler::_updatePeakMemoryFunction , std::ref( *this ) , ms );
172 _spawnedSampler = true;
173 }
174 else _spawnedSampler = false;
175 }
176
177 ~Profiler( void )
178 {
179 if( _spawnedSampler )
180 {
181 _terminate = true;
182 _thread.join();
183 }
184 }
185
186 void reset( void )
187 {
188 _t = Time();
189 if( _spawnedSampler )
190 {
191 std::lock_guard< std::mutex > lock( _mutex );
192 _currentPeak = 0;
193 }
194 else _currentPeak = 0;
195 }
196
197 void update( void )
198 {
199 size_t currentPeak = getCurrentRSS();
200 if( _spawnedSampler )
201 {
202 std::lock_guard< std::mutex > lock( _mutex );
203 if( currentPeak>_currentPeak ) _currentPeak = currentPeak;
204 }
205 else if( currentPeak>_currentPeak ) _currentPeak = currentPeak;
206 }
207
208 std::string operator()( bool showTime=true ) const
209 {
210 std::stringstream ss;
211 double dt = Time()-_t;
212 double localPeakMB = ( (double)_currentPeak )/(1<<20);
213 double globalPeakMB = ( (double)getPeakRSS() )/(1<<20);
214 {
215 StreamFloatPrecision sfp( ss , 1 );
216 if( showTime ) ss << dt << " (s), ";
217 ss << localPeakMB << " (MB) / " << globalPeakMB << " (MB)";
218 }
219 return ss.str();
220 }
221
222 friend std::ostream &operator << ( std::ostream &os , const Profiler &profiler ){ return os << profiler(); }
223
224 protected:
225 std::thread _thread;
226 std::mutex _mutex;
227 double _t;
228 std::atomic< bool > _spawnedSampler;
229 std::atomic< size_t > _currentPeak;
230 std::atomic< bool > _terminate;
231
232 void _updatePeakMemoryFunction( unsigned int ms )
233 {
234 while( true )
235 {
236 std::this_thread::sleep_for( std::chrono::milliseconds( ms ) );
237 update();
238 if( _terminate ) return;
239 }
240 };
241 };
242
243 struct MemoryInfo
244 {
245 static size_t Usage( void ){ return getCurrentRSS(); }
246 static int PeakMemoryUsageMB( void ){ return (int)( getPeakRSS()>>20 ); }
247 };
248
249 #if defined( _WIN32 ) || defined( _WIN64 )
250 inline void SetPeakMemoryMB( size_t sz )
251 {
252 sz <<= 20;
253 SIZE_T peakMemory = sz;
254 HANDLE h = CreateJobObject( NULL , NULL );
255 AssignProcessToJobObject( h , GetCurrentProcess() );
256
257 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
258 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY;
259 jeli.JobMemoryLimit = peakMemory;
260 if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) ) MK_WARN( "Failed to set memory limit" );
261 }
262 #else // !_WIN32 && !_WIN64
263 inline void SetPeakMemoryMB( size_t sz )
264 {
265 sz <<= 20;
266 struct rlimit rl;
267 getrlimit( RLIMIT_AS , &rl );
268 rl.rlim_cur = sz;
269 setrlimit( RLIMIT_AS , &rl );
270 }
271 #endif // _WIN32 || _WIN64
272
273 /*
274 * Author: David Robert Nadeau
275 * Site: http://NadeauSoftware.com/
276 * License: Creative Commons Attribution 3.0 Unported License
277 * http://creativecommons.org/licenses/by/3.0/deed.en_US
278 */
279
280 /**
281 * Returns the peak (maximum so far) resident set size (physical
282 * memory use) measured in bytes, or zero if the value cannot be
283 * determined on this OS.
284 */
285 inline size_t getPeakRSS( )
286 {
287 #if defined(_WIN32)
288 /* Windows -------------------------------------------------- */
289 PROCESS_MEMORY_COUNTERS info;
290 GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
291 return (size_t)info.PeakWorkingSetSize;
292
293 #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
294 /* AIX and Solaris ------------------------------------------ */
295 struct psinfo psinfo;
296 int fd = -1;
297 if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 )
298 return (size_t)0L; /* Can't open? */
299 if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) )
300 {
301 close( fd );
302 return (size_t)0L; /* Can't read? */
303 }
304 close( fd );
305 return (size_t)(psinfo.pr_rssize * 1024L);
306
307 #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
308 /* BSD, Linux, and OSX -------------------------------------- */
309 struct rusage rusage;
310 getrusage( RUSAGE_SELF, &rusage );
311 #if defined(__APPLE__) && defined(__MACH__)
312 return (size_t)rusage.ru_maxrss;
313 #else
314 return (size_t)(rusage.ru_maxrss * 1024L);
315 #endif
316
317 #else
318 /* Unknown OS ----------------------------------------------- */
319 return (size_t)0L; /* Unsupported. */
320 #endif
321 }
322
323
324
325
326
327 /**
328 * Returns the current resident set size (physical memory use) measured
329 * in bytes, or zero if the value cannot be determined on this OS.
330 */
331 inline size_t getCurrentRSS( )
332 {
333 #if defined(_WIN32) || defined( _WIN64 )
334 /* Windows -------------------------------------------------- */
335 PROCESS_MEMORY_COUNTERS info;
336 GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
337 return (size_t)info.WorkingSetSize;
338
339 #elif defined(__APPLE__) && defined(__MACH__)
340 /* OSX ------------------------------------------------------ */
341 struct mach_task_basic_info info;
342 mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
343 if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO,
344 (task_info_t)&info, &infoCount ) != KERN_SUCCESS )
345 return (size_t)0L; /* Can't access? */
346 return (size_t)info.resident_size;
347
348 #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
349 /* Linux ---------------------------------------------------- */
350 long rss = 0L;
351 FILE* fp = NULL;
352 if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
353 return (size_t)0L; /* Can't open? */
354 if ( fscanf( fp, "%*s%ld", &rss ) != 1 )
355 {
356 fclose( fp );
357 return (size_t)0L; /* Can't read? */
358 }
359 fclose( fp );
360 return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);
361
362 #else
363 /* AIX, BSD, Solaris, and Unknown OS ------------------------ */
364 return (size_t)0L; /* Unsupported. */
365 #endif
366 }
367 }
368
369 #endif // MY_MISCELLANY_INCLUDED