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

51
LINES

< > BotCompany Repo | #1001403 // Thread CPU time experimentation (ThreadMXBean)

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

Libraryless. Click here for Pure Java version (107L/2K/5K).

!747

m {
  static Map<Long, Thread> idToThread;
  
  p {
    ThreadMXBean mx = ManagementFactory.getThreadMXBean();
    
    // just for fun
    print("Total started thread count: " + mx.getTotalStartedThreadCount());
    
    boolean cpuTimeSupported = mx.isThreadCpuTimeSupported();
    print("CPU time supported: " + cpuTimeSupported);
    if (!cpuTimeSupported) fail("No CPU time info available on platform.");
    
    long[] threads = mx.getAllThreadIds();
    
    long time = now();
    L<Thread> l = getAllThreads();
    print((now()-time) + " ms for getAllThreads()");
    print(l.size() + " threads");
    
    idToThread = new TreeMap();
    for (Thread t : l)
      idToThread.put(t.getId(), t);
      
    for (long id : threads) {
      long nano = mx.getThreadCpuTime(id);
      long ms = nano/1000000;
      Thread t = idToThread.get(id);
      if (t == null)
        print("? thread not found: " + id);
      else
        print("Thread " + quote(t.getName()) + ": CPU time = " + ms + " ms");
    }
    
  }
  
  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;
  }
}

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1001403
Snippet name: Thread CPU time experimentation (ThreadMXBean)
Eternal ID of this version: #1001403/1
Text MD5: f99e1606cbf6aed395304b56a48929f4
Transpilation MD5: 2066c8e5b704863a91e87d12ed79d6f0
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-10-14 17:47:37
Source code size: 1606 bytes / 51 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 713 / 760
Referenced in: [show references]