1、CPU使用率获取,因为我要用JNA调用,所以用c++调用windowAPI,编译成Dll文件;dll的代码如下:
// DllTest.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "iostream" #include "stdafx.h" #define _WIN32_WINNT 0x0501 #include#define MYLIBAPI extern "C" __declspec( dllexport ) /* 要返回的函数声明 */ MYLIBAPI void getCpuInfo(int wait,double* d); /* 函数的定义 */ //转换FILETIME类型 __int64 CompareFileTime ( FILETIME time1, FILETIME time2 ) { __int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime ; __int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime ; return (b - a); } //函数的实体 /*wait是统计多长时间内的cpu使用率 d是返回的数组 */ void getCpuInfo(int wait,double* d){ HANDLE hEvent; BOOL res ; FILETIME preidleTime; FILETIME prekernelTime; FILETIME preuserTime; FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; res = GetSystemTimes( &idleTime, &kernelTime, &userTime ); preidleTime = idleTime; prekernelTime = kernelTime; preuserTime = userTime ; hEvent = CreateEvent (NULL,FALSE,FALSE,NULL); // 初始值为 nonsignaled ,并且每次触发后自动设置为nonsignaled WaitForSingleObject( hEvent,wait); //等待500毫秒 res = GetSystemTimes( &idleTime, &kernelTime, &userTime ); int idle = CompareFileTime( preidleTime,idleTime); int kernel = CompareFileTime( prekernelTime, kernelTime); int user = CompareFileTime(preuserTime, userTime); //cpu使用率的计算 double cpu = (kernel +user - idle) *100.0/(kernel+user); //cpu空闲率的计算 double cpuidle = ( idle) *100.0/(kernel+user); d[0] =cpu; d[1] = cpuidle; }
2、JNA代码的定义
package com.ligson.jna; import com.sun.jna.Library; import com.sun.jna.Native; //声明 interface MyDllLib extends Library { /* DllTest.dll是我编译后的dll文件,放在项目的根目录 */ MyDllLib INSTANCE = (MyDllLib) Native.loadLibrary("DllTest.dll", MyDllLib.class); /* 这个与c++中函数的定义一样,唯一不同的double[] d没用用指针,但是数组的本身就是指针, */ public void getCpuInfo(int wait, double[] d); } public class GetCpuInfo { static MyDllLib myDllLib = MyDllLib.INSTANCE; public static double getCpu(int wait) { //声明返回值 double[] d = new double[2]; myDllLib.getCpuInfo(wait,d); return d[0]; } }
3、Web环境用grails框架,grails框架语法简单,各种东西定义都很方便,Controller的定义
package hf import grails.converters.JSON class CpuMonitorController { static List list = []; static Map result = [:]; def index = { render(view: 'cpu'); } def getCpuInfo = { double d = com.ligson.jna.GetCpuInfo.getCpu(500); def l = [:]; l.x = new Date().getTime(); l.y = d; list.add(l); result.x = l.x; result.y = l.y; //返回json格式,x轴以时间为准,y轴以cpu占有率为准 return render(result as JSON); } }
4、cpu.gsp的代码:
<%-- Created by IntelliJ IDEA. User: Administrator Date: 12-1-10 Time: 下午7:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" %>Simple GSP page
5、漂亮的效果图:
6、我的dll库文件在下面,欢迎大家下载使用