Skip to content

Instantly share code, notes, and snippets.

@quininer
Last active August 29, 2015 14:12
Show Gist options
  • Save quininer/616f6e421886db4a64f8 to your computer and use it in GitHub Desktop.
Save quininer/616f6e421886db4a64f8 to your computer and use it in GitHub Desktop.
SwapView
#!/usr/bin/dmd -run
import std.stdio, std.file, std.path, std.string, std.conv, std.math;
struct SwapMap {
string pid;
double size = 0;
string cmd;
}
SwapMap[] mapsort(SwapMap[] swapmap){
if(swapmap.length <= 1)
return swapmap;
SwapMap[] lmap;
SwapMap[] rmap;
foreach(SwapMap swaps; swapmap[1 .. swapmap.length]){
if(swaps.size < swapmap[0].size){
lmap ~= swaps;
}else{
rmap ~= swaps;
}
}
return mapsort(lmap)~swapmap[0 .. 1]~mapsort(rmap);
}
string filesize(double size){
string units = "KMGT";
double left = size.abs();
int unit = -1;
while(left > 1100 && unit < 3){
left /=1024;
unit += 1;
}
if(unit == -1){
return format("%dB", to!int(size));
}else{
if(size < 0)
left = -left;
return format("%.1%siB", left, units[unit]);
}
}
SwapMap getswapfor(string pid){
SwapMap swaps;
try{
File file = File("/proc/"~pid~"/smaps", "r");
foreach(string line; lines(file)){
line = chomp(line);
/*
// 据说性能比较好?
char[] buf;
while (!file.eof()){
file.readln(buf);
string line = chomp(to!string(buf));
*/
if(!line.indexOf("Swap:")){
swaps.size += to!int(line.split()[1]);
}
}
file.close();
if(!swaps.size)
return swaps;
swaps.pid = pid;
swaps.size = swaps.size*1024;
swaps.text = chomp(readText("/proc/"~pid~"/cmdline"));
}catch(StdioException e){
writeln(e.msg);
return swaps;
}
return swaps;
}
SwapMap[] getswaps(){
SwapMap[] swaps;
SwapMap tmps;
string pid;
foreach(DirEntry dirs; dirEntries("/proc", SpanMode.shallow)){
pid = baseName(dirs.name);
if(pid.isNumeric()){
tmps = getswapfor(pid);
if(tmps.size)
swaps ~= tmps;
}
}
return swaps;
}
void main(){
string m = "%5s %9s %s";
int total = 0;
writeln(format(m , "PID", "SWAP", "COMMAND"));
SwapMap[] swapmap = mapsort(getswaps());
foreach(SwapMap swaps; swapmap){
total += swaps.size;
writeln(format(m, swaps.pid, filesize(swaps.size), swaps.cmd));
}
writeln("Total: ", filesize(total));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment