Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

161
LINES

< > TinyBrain | #1001405 - Java CPU Monitor Bot (+ System Load)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (3904L/27K/89K).

!7

// All numbers per core

import com.sun.management.OperatingSystemMXBean; 

static boolean verbose = false;
static long interval = 1000; // ms

static Map<Long, Thread> idToThread;
static new WeakHashMap<Thread, Info> infoMap;

static class Info {
  long cpuTime, measuredWhen; // all in milliseconds
  double percentage; // percentage of CPU used
}

static ThreadMXBean mx;
static boolean cpuTimeSupported;

static double totalPercentage; // all threads combined
static long lastMeasured;

p {
  mx = ManagementFactory.getThreadMXBean();
  cpuTimeSupported = mx.isThreadCpuTimeSupported();
  if (!cpuTimeSupported) fail("No CPU time info available on platform.");
  
  makeAndroid3("CPU Monitor Bot.");
  
  thread "Java CPU Monitor" {
    while (licensed()) {
      pcall {
        monitor();
        if (verbose)
          printMostActiveThread();
      }
      sleep(interval);
    }
  }
}
  
static synchronized void monitor() {    
  L<Thread> threads = getAllThreads();
  new WeakHashMap<Thread, Info> newInfoMap;
  totalPercentage = 0;
  
  for (Thread t : threads) {
    Info info = infoMap.get(t);
    if (info == null) info = new Info;
    newInfoMap.put(t, info);
    
    long nano = 0;
    pcall { nano = mx.getThreadCpuTime(t.getId()); }
    long measured = now();
    long ms = nano/1000000;
    
    if (info.measuredWhen != 0) {
      long elapsed = measured - info.measuredWhen;
      long used = ms-info.cpuTime;
      info.percentage = Math.max(0, Math.min(100, used*100.0/elapsed));
      totalPercentage += info.percentage;
    }
    
    info.measuredWhen = measured;
    info.cpuTime = ms;
  }
  
  lastMeasured = now();
  infoMap = newInfoMap;
}

static synchronized Thread getMostActiveThread() {  
  Thread mostActive = null;
  double highest = 0.0;
  
  for (Map.Entry<Thread, Info> e : infoMap.entrySet()) {
    Thread t = e.getKey();
    Info info = e.getValue();
    if (mostActive == null || info.percentage > highest) {
      mostActive = t;
      highest = info.percentage;
    }
  }
  
  return mostActive;
}
  
static synchronized void printMostActiveThread() {
  Thread mostActive = getMostActiveThread();
  if (mostActive == null)
    print("No info");
  else
    print("Total CPU used by this VM: " + formatDouble(totalPercentage, 1) + "%. Most active thread: " + mostActive.getName() + " (" + formatDouble(infoMap.get(mostActive).percentage, 1) + "% CPU)");
}

static L<Thread> getAllThreads() {
  ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
  ThreadGroup parentGroup;
  while ( ( parentGroup = rootGroup.getParent() ) != null )
    rootGroup = parentGroup;
  Thread[] threads = new Thread[rootGroup.activeCount()];
  int n;
  while ((n = rootGroup.enumerate(threads, true)) == threads.length)       threads = new Thread[threads.length*2];
  L<Thread> l = new ArrayList<Thread>(n);
  for (int i = 0; i < n; i++) l.add(threads[i]);
  ret l;
}

synchronized answer {
  if (match("cpu", s) || match("cpu usage", s)) {
    S a = formatDouble(totalPercentage, 2) + "% Java threads";
    pcall {
      OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
      
      double x = osBean.getProcessCpuLoad()*numberOfCores()*100, y = osBean.getSystemCpuLoad()*numberOfCores()*100;
      a += ". " + formatDouble(x, 1) + "% this process, " 
        + formatDouble(max(0, y-x), 1) + "% other processes"; 
    }
    return a;
  }
    
  if (match3("most active thread", s)) {
    Thread t = getMostActiveThread();
    return t == null ? "Sorry, no info." : format3("Thread name: *, cpu: *", t.getName(), formatDouble(totalPercentage, 2) + "%");
  }
  
  if (match3("cpu: get measurement interval", s))
    ret interval + " ms";
    
  if (match3("cpu: are you measuring", s))
    ret "Yes.";
    
  if (match3("cpu: get last measurement time", s))
    ret "" + lastMeasured;
    
  if "cpu: list all threads" {
    new L<S> l;
    for (Map.Entry<Thread, Info> e : infoMap.entrySet()) {
      Thread t = e.getKey();
      Info info = e.getValue();
      l.add(formatDouble(info.percentage, 1) + "% " + format("*", t.getName()));
    }
    ret slackSnippet(fromLines(l));
  }
  
  if "system load"
    ret "System load: " + formatDouble(ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(), 2);
    
  if "cpu: processors" {
    java.lang.management.OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    ret "I have " + n(bean.getAvailableProcessors(), bean.getArch() +  " processor") + ".";
  }
}

// in percent
static synchronized double getInProcessCPU() {
  ret totalPercentage;
}

Author comment

Began life as a copy of #1001404

download  show line numbers  debug dex   

Travelled to 6 computer(s): ajlfxifxfcul, cfunsshuasjs, dhtvkmknsjym, onxytkatvevr, teubizvjbppd, tvejysmllsmz

No comments. add comment

Snippet ID: #1001405
Snippet name: Java CPU Monitor Bot (+ System Load)
Eternal ID of this version: #1001405/4
Text MD5: 284da034f919d3f6866ab01e535c3f61
Transpilation MD5: 22cd393e7875075704aee8c37349421d
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-09-14 02:20:07
Source code size: 4782 bytes / 161 lines
Pitched / IR pitched: No / No
Views / Downloads: 235 / 820
Version history: 3 change(s)
Referenced in: [show]