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

165
LINES

< > BotCompany Repo | #1001405 // Java CPU Monitor Bot (+ System Load)

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

Libraryless. Click here for Pure Java version (6903L/48K/160K).

!7

// All numbers per core

import com.sun.management.OperatingSystemMXBean; 

static boolean verbose = false;
static long interval = 1000; // ms
sbool measureThreads = true;

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 volatile double totalPercentage; // all threads combined
static long lastMeasured;

// info about HotSpot compilation
static double compilationPercentage;
static long lastCompilationTime, compilationTimeMeasured;

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 && measureThreads)
          printMostActiveThread();
      }
      sleep(interval);
    }
  }
}
  
svoid monitor {
  lock programLock();
  
  long ct = hotSpotCompilationTime();
  long ctm = now();
  if (compilationTimeMeasured != 0)
    compilationPercentage = 100*doubleRatio(ct-lastCompilationTime, ctm-compilationTimeMeasured);
  compilationTimeMeasured = ctm;
  lastCompilationTime = ct;

  if (!measureThreads) ret;
  L<Thread> threads = allThreads_fast();
  new WeakHashMap<Thread, Info> newInfoMap;
  double _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 = max(0, min(100, used*100.0/elapsed));
      _totalPercentage += info.percentage;
    }
    
    info.measuredWhen = measured;
    info.cpuTime = ms;
  }
  
  totalPercentage = _totalPercentage;
  lastMeasured = now();
  infoMap = newInfoMap;
}

static Thread getMostActiveThread() {
  lock programLock();
  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 void printMostActiveThread() {
  lock programLock();
  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)");
}

answer {
  lock programLock();
  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(systemLoad(), 2);
    
  if "cpu: processors" {
    java.lang.management.OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    ret "I have " + n(bean.getAvailableProcessors(), bean.getArch() +  " processor") + ".";
  }
}

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

Author comment

Began life as a copy of #1001404

download  show line numbers  debug dex  old transpilations   

Travelled to 18 computer(s): ajlfxifxfcul, aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, dhtvkmknsjym, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1001405
Snippet name: Java CPU Monitor Bot (+ System Load)
Eternal ID of this version: #1001405/11
Text MD5: f436293bce4ba1887238817a29caffd9
Transpilation MD5: 409c8569772205864d23cc15402bcc88
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-07-26 10:17:06
Source code size: 4745 bytes / 165 lines
Pitched / IR pitched: No / No
Views / Downloads: 758 / 8093
Version history: 10 change(s)
Referenced in: #1002592 - Graphical CPU Meter (LIVE)
#1007527 - Test Bot Clean-Up
#1010389 - CPU Monitor + Utilize All Cores
#1016652 - Java CPU % [Dyn Module]
#1018568 - Java CPU % Ultra-Shortened [dev.]
#1024200 - HotSpot Compilation CPU % [Dyn Module]
#1024201 - Java + HotSpot Compilation CPU % [Dyn Module]
#3000169 - Answer for stefanreich
#3000174 - Answer for stefanreich
#3000175 - Answer for stefanreich
#3000176 - Answer for stefanreich
#3000177 - Answer for stefanreich
#3000179 - Answer for stefanreich
#3000180 - Answer for stefanreich
#3000181 - Answer for stefanreich
#3000182 - Answer for stefanreich
#3000184 - Answer for stefanreich
#3000185 - Answer for stefanreich
#3000202 - Answer for stefanreich (>> T conversion bot)
#3000203 - Answer for stefanreich (>> timing hello bot)
#3000208 - Answer for bgrgndz (>> list sub bots)
#3000209 - Answer for bgrgndz (>> list sub bots)
#3000238 - Answer for stefanreich (>> t power bot)
#3000369 - Answer for Stefan (>> list sub bots)
#3000376 - Answer for stefanreich (>> list sub bots)
#3000377 - Answer for stefanreich (>> timing eleu?)
#3000380 - Answer for stefanreich (>> list sub bots)
#3000381 - Answer for speedforce (>> list sub bots)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)