2013-08-19 46 views
0

我想監視「」Jboss 7爲「」CPU使用率的百分比,我可以使用JMX來實現嗎?當我寫這個功能,我得到CPU時間,而不是CPU百分比...由JBoss 7使用的CPU百分比7

public String getCpuUsage(){ 
    try { 
     Method m=op.getClass().getDeclaredMethod("getProcessCpuTime"); 
     m.setAccessible(true); 
     Object value=null; 
     value=m.invoke(op); 
     return value+""; 
    } catch (SecurityException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (NoSuchMethodException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalArgumentException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return null; 
} 

如何計算JBoss CPU百分比?

回答

0

進程cpu時間是自進程啓動以來進程使用的總納秒數。因此,要獲得百分比,您需要另外2條信息:

  1. CPU的數量。這可從OperatingSystemMXBean.getAvailableProcessors()Runtime.availableProcessors()獲得。
  2. 在進程cpu時間累積期間已過去的相應掛鐘時間,最好使用System.nanoTime()進行,因爲它提供與進程cpu時間相同的「單位」。

實施項目#2的上方是週期性地輪詢過程cpu時間定期期間,第一輪詢之後,經過的掛鐘時間將是當前System.nanoTime()的最佳方式減去之前投票期間收集的數據。

所以,現在你有:

  • 經過的掛鐘時間(這一段的時候,減去上期的時間)調用此X
  • 經過的過程CPU時間(這一段的時候,減去最後期限的時間)致電Y
  • CPU的數量。調用此Ç

百分比利用將是Y /(X X C)* 100

以下是一個演示這是一個快速和骯髒的Groovy腳本:

import java.lang.management.*; 
import java.util.concurrent.*; 

osx = ManagementFactory.getOperatingSystemMXBean(); 
cores = osx.getAvailableProcessors(); 

// Factorial to keep the process busy so we can see some actual activity 
factorial = { n -> 
    int fact = 1; 
    int i = 1; 
    while(i <= n) { 
     i++; 
     fact *= i; 
    } 
    return fact; 
} 


long elapsedTime = -1, startTime = -1; 
long elapsedCpu = -1, startCpu = -1;; 

for(i in 0..20) { 
    startTime = System.nanoTime(); 
    startCpu = osx.getProcessCpuTime(); 
    CountDownLatch latch = new CountDownLatch(cores); 
    for(x in 1..cores) { 
     Thread.startDaemon() { 
      factorial(1000000); 
      latch.countDown(); 
     } 
    } 
    latch.await(); 
    elapsedTime = System.nanoTime()-startTime; 
    elapsedCpu = osx.getProcessCpuTime()-startCpu; 
    percUsage = (elapsedCpu/(elapsedTime* cores)) *100; 
    println "Percent Usage:$percUsage %"; 
} 

的輸出:

Percent Usage:51.5167066100 % 
Percent Usage:53.5206121100 % 
Percent Usage:55.3874037900 % 
Percent Usage:59.8187255600 % 
Percent Usage:60.0488511300 % 
Percent Usage:68.3172332900 % 
Percent Usage:45.0529180000 % 
Percent Usage:58.3662459200 % 
Percent Usage:62.6933609700 % 
Percent Usage:60.1530673000 % 
Percent Usage:69.0448532600 % 
Percent Usage:52.0072152200 % 
Percent Usage:57.1837311400 % 
Percent Usage:65.8311579500 % 
Percent Usage:66.3076807600 % 
Percent Usage:69.8803721800 % 
Percent Usage:28.5111361300 % 
Percent Usage:40.1093035100 % 
Percent Usage:60.9499459700 % 
Percent Usage:68.7113809300 % 
Percent Usage:71.8252480400 % 

您應該很容易比我做得更好。