ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/proc_mem.cpp
Revision: 264
Committed: Mon Aug 27 18:21:11 2012 UTC (7 years, 2 months ago) by gpertea
File size: 1732 byte(s)
Log Message:
minor refactoring etc

Line User Rev File contents
1 gpertea 18 #include <unistd.h>
2     #include <string>
3     #include <ios>
4     #include <fstream>
5     //////////////////////////////////////////////////////////////////////////////
6     // process_mem_usage(double &, double &) - takes two doubles by reference,
7     // attempts to read the system-dependent data for a process' virtual memory
8     // size and resident set size, and return the results in KB.
9     //
10     // On failure, returns 0.0, 0.0
11    
12     void process_mem_usage(double& vm_usage, double& resident_set) {
13     using std::ios_base;
14     using std::ifstream;
15     using std::string;
16     vm_usage = 0.0;
17     resident_set = 0.0;
18     // 'file' stat seems to give the most reliable results
19     ifstream stat_stream("/proc/self/stat",ios_base::in);
20     // dummy vars for leading entries in stat that we don't care about
21     string pid, comm, state, ppid, pgrp, session, tty_nr;
22     string tpgid, flags, minflt, cminflt, majflt, cmajflt;
23     string utime, stime, cutime, cstime, priority, nice;
24     string O, itrealvalue, starttime;
25    
26     // the two fields we want
27     //
28     unsigned long vsize;
29     long rss;
30    
31     stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
32     >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
33     >> utime >> stime >> cutime >> cstime >> priority >> nice
34     >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
35    
36     stat_stream.close();
37    
38 gpertea 264
39 gpertea 18 long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
40     vm_usage = vsize / 1024.0;
41     resident_set = rss * page_size_kb;
42     }
43    
44     void print_mem_usage() {
45     double vs, rs;
46     process_mem_usage(vs,rs);
47     vs/=1024;
48     rs/=1024;
49     fprintf(stderr, "VMSize: %6.1fMB\tRSize: %6.1fMB\n", vs, rs);
50     }