ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/proc_mem.cpp
Revision: 18
Committed: Mon Jul 18 21:00:21 2011 UTC (7 years, 11 months ago) by gpertea
File size: 1731 byte(s)
Log Message:
added a few more source files, test code

Line File contents
1 #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 long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
39 vm_usage = vsize / 1024.0;
40 resident_set = rss * page_size_kb;
41 }
42
43 void print_mem_usage() {
44 double vs, rs;
45 process_mem_usage(vs,rs);
46 vs/=1024;
47 rs/=1024;
48 fprintf(stderr, "VMSize: %6.1fMB\tRSize: %6.1fMB\n", vs, rs);
49 }