增加在linux下查询程序内存使用量的接口

This commit is contained in:
邹晓航
2014-10-23 13:31:32 +08:00
parent 78a59a83b1
commit 995d7230b2
2 changed files with 16 additions and 10 deletions

View File

@@ -29,12 +29,19 @@ namespace TinySTL{
} }
size_t ProfilerInstance::memory(MemoryUnit mu){ size_t ProfilerInstance::memory(MemoryUnit mu){
size_t memory = 0;
#ifdef WIN32 #ifdef WIN32
PROCESS_MEMORY_COUNTERS pmc; PROCESS_MEMORY_COUNTERS pmc;
HANDLE hProcess = GetCurrentProcess(); HANDLE hProcess = GetCurrentProcess();
if (!GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) if (!GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)))
throw std::runtime_error("GetProcessMemoryInfo failed"); throw std::runtime_error("GetProcessMemoryInfo failed");
size_t memory = 0; CloseHandle(hProcess);
#else
struct rusage usage;
if(getrusage(RUSAGE_SELF, &usage) == -1)
throw std::runtime_error("getrusage failed");
memory = usage.ru_maxrss / 1024;//如果某些linux平台不完全支持getrusage则ru_maxrss总是返回0
#endif
switch (mu){ switch (mu){
case MemoryUnit::KB_: case MemoryUnit::KB_:
memory = pmc.WorkingSetSize KB; memory = pmc.WorkingSetSize KB;
@@ -46,10 +53,7 @@ namespace TinySTL{
memory = pmc.WorkingSetSize GB; memory = pmc.WorkingSetSize GB;
break; break;
} }
CloseHandle(hProcess);
return memory; return memory;
#else
#endif
} }
} }
} }

View File

@@ -14,6 +14,8 @@
#include <Psapi.h> #include <Psapi.h>
#pragma comment(lib, "psapi.lib") #pragma comment(lib, "psapi.lib")
#else #else
#include <sys/resource>
#include <sys/time.h>
#endif #endif
namespace TinySTL{ namespace TinySTL{
@@ -34,14 +36,14 @@ namespace TinySTL{
static TimePoint startTime; static TimePoint startTime;
static TimePoint finishTime; static TimePoint finishTime;
public: public:
static void start(); static void start();//开始计时
static void finish(); static void finish();//结束计时
static void dumpDuringTime(std::ostream& os = std::cout); static void dumpDuringTime(std::ostream& os = std::cout);//打印时间
static double second(); static double second();//以秒为单位返回时间
static double millisecond(); static double millisecond();//以毫秒为单位返回时间
static size_t memory(MemoryUnit mu = MemoryUnit::KB_); static size_t memory(MemoryUnit mu = MemoryUnit::KB_);//查询当前程序的内存使用量
}; };
} }
} }