当前页面: 开发资料首页 → Java 专题 → 在Java应用程序中监视CPU的使用
摘要: 在Java应用程序中监视CPU的使用
public staticnative long getProcessCPUTime();
JNIEXPORT jlong JNICALLJava_com_vladium_utils_SystemInformation_getProcessCPUTime (JNIEnv * env, jclass cls)
JNIEXPORT jlong JNICALLJava_com_vladium_utils_SystemInformation_getProcessCPUTime (JNIEnv * env, jclass cls){
FILETIME creationTime, exitTime, kernelTime, userTime; GetProcessTimes (s_currentProcess, & creationTime, & exitTime, & kernelTime, & userTime);
return (jlong) ((fileTimeToInt64 (& kernelTime) + fileTimeToInt64 (& userTime)) /
(s_numberOfProcessors * 10000));}
static HANDLE s_currentProcess;static int s_numberOfProcessors;JNIEXPORT jint JNICALLJNI_OnLoad (JavaVM * vm, void * reserved){
SYSTEM_INFO systemInfo;
s_currentProcess = GetCurrentProcess ();
GetSystemInfo (& systemInfo);
s_numberOfProcessors = systemInfo.dwNumberOfProcessors; return JNI_VERSION_1_2;}
private static final String SILIB = "silib";
static {
try {
System.loadLibrary (SILIB);
} catch (UnsatisfiedLinkError e) { System.out.println ("native lib '" + SILIB + "' not found in 'java.library.path': " + System.getProperty ("java.library.path")); throw e; // re-throw } }
public static final class CPUUsageSnapshot {
private CPUUsageSnapshot (long time, long CPUTime) {
m_time = time;
m_CPUTime = CPUTime; } public final long m_time, m_CPUTime; } // end of nested class public static CPUUsageSnapshot makeCPUUsageSnapshot () { return new CPUUsageSnapshot (System.currentTimeMillis (), getProcessCPUTime ()); } public static double getProcessCPUUsage (CPUUsageSnapshot start, CPUUsageSnapshot end) { return ((double)(end.m_CPUTime - start.m_CPUTime)) / (end.m_time - start.m_time); }
public void run () {
while (! isInterrupted ()) {
final SystemInformation.CPUUsageSnapshot snapshot = SystemInformation.makeCPUUsageSnapshot (); notifyListeners (snapshot);
try {
sleep (sleepTime); }
catch (InterruptedException e) { return; } } }
public static void main (String [] args) throws Exception { if (args.length == 0) throw new IllegalArgumentException ("usage: CPUmon");
CPUUsageThread monitor = CPUUsageThread.getCPUThreadUsageThread (); CPUmon _this = new CPUmon ();
Class app = Class.forName (args [0]);
Method appmain = app.getMethod ("main", new Class [] {String[].class});
String [] appargs = new String [args.length - 1]; System.arraycopy (args, 1, appargs, 0, appargs.length); monitor.addUsageEventListener (_this); monitor.start (); appmain.invoke (null, new Object [] {appargs}); }