1 #ifndef __MEMORY_DBG
2 #define __MEMORY_DBG
3 
4 #include <vector>
5 #include "std_util.h"
6 
7 #ifdef WIN32
8 	#define _CRTDBG_MAP_ALLOC
9 	#include <crtdbg.h>
10 #else
11 #include <sys/time.h>
12 #include <sys/resource.h>
13 #endif
14 
15 //#define NO_BERKELEY
16 struct MemDbgBase{
CheckHeapMemDbgBase17 	static bool CheckHeap(int level){level = 0;return true;};
18 };
19 
20 #ifdef WIN32
21 struct MemDbg: public MemDbgBase{
LevelMemDbg22 	static int & Level() {static int   level = 0; return level;}
CheckHeapMemDbg23 	static bool CheckHeap(int level){
24                 #ifdef WIN32
25 		return (level>Level())?(0!=_CrtCheckMemory()):true;
26 		#else
27 		return true;
28 		#endif
29 	}
SetBreakAllocMemDbg30 	static void SetBreakAlloc(int value ){
31                 #ifdef WIN32
32 		_CrtSetBreakAlloc(value );
33 		#endif
34 		value = 0;}
DumpMemoryLeaksMemDbg35 	static void DumpMemoryLeaks(){
36                 #ifdef WIN32
37 		_CrtDumpMemoryLeaks();
38 		#endif
39 	}
40 
NVMemDbg41 	static std::vector<_CrtMemState> &  NV(){static std::vector<_CrtMemState> name_value;return   name_value;}
42 
MemStateMemDbg43 	static _CrtMemState & MemState(){static _CrtMemState cms; return cms; }
AllMemDbg44 	static bool & All(){static bool allocated = false; return allocated;}
SetPointMemDbg45 	static void SetPoint(unsigned int   n){
46 		n=n;
47 		if(!All())  NV().resize(128);
48                 #ifdef WIN32
49 		_CrtMemCheckpoint(& NV()[n]);
50 		#endif
51 	}
MemFromPointMemDbg52 	static unsigned int MemFromPoint(unsigned int p){
53                 #ifdef WIN32
54 		_CrtMemCheckpoint(&MemState());
55 		#endif
56 		return MemState().lTotalCount -  NV()[p].lTotalCount;
57 	}
EndMemDbg58 	static void End(){Delete(NV());}
59 };
60 #else
61 #define  _CrtMemState int
62 struct MemDbg: public MemDbgBase{
AllMemDbg63 	static bool & All(){static bool allocated = false; return allocated;}
LevelMemDbg64 	static int & Level() {static int  level = 0; return level;}
CheckHeapMemDbg65 	static bool CheckHeap(int level){ return true;level = 0; }
SetBreakAllocMemDbg66 	static void SetBreakAlloc(int value ){value=0; }
DumpMemoryLeaksMemDbg67 	static void DumpMemoryLeaks(){ }
NVMemDbg68 	static std::vector<rusage> &  NV(){static std::vector<rusage> name_value;return   name_value;}
69 
70 
MemFromPointMemDbg71 static unsigned int MemFromPoint(unsigned int p){
72 		int res;
73 		rusage ru;
74 		res = getrusage(RUSAGE_SELF,&ru);
75 		return ru.ru_maxrss - NV()[p].ru_maxrss;
76 }
77 
SetPointMemDbg78 static void SetPoint(unsigned int   n){
79 		n=n;
80 		if(!All())  {NV().resize(128);All() = true;}
81 		int res;
82 		rusage ru;
83 		res = getrusage(RUSAGE_SELF,&ru);
84 		NV()[n].ru_maxrss = ru.ru_maxrss;
85 }
EndMemDbg86 static void End(){Delete(NV());}
87 
88 };
89 #endif
90 
91 #endif
92