Highcharts动态曲线图(使用jna监视cpu使用率)

fmms 12年前
     <p><span style="font-size:medium;">1、CPU使用率获取,因为我要用JNA调用,所以用c++调用windowAPI,编译成Dll文件;dll的代码如下:</span> </p>    <pre class="brush:cpp; toolbar: true; auto-links: false;">// DllTest.cpp : Defines the exported functions for the DLL application. //  #include "stdafx.h" #include "iostream" #include "stdafx.h" #define _WIN32_WINNT   0x0501 #include <Windows.h> #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; }</pre>    <p><span style="font-size:medium;">2、JNA代码的定义</span> </p>    <pre class="brush:java; toolbar: true; auto-links: false;">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];     } }</pre>    <p><span style="font-size:medium;">3、Web环境用grails框架,grails框架语法简单,各种东西定义都很方便,Controller的定义</span> </p>    <pre class="brush:java; toolbar: true; auto-links: false;">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);   } }</pre>    <p><span style="font-size:medium;">4、cpu.gsp的代码:</span> </p>    <pre class="brush:html; toolbar: true; auto-links: false;"><%--   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" %> <html> <head>   <title>Simple GSP page</title>   <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery-1.6.js')}"></script>   <!--这个是必须的,highChart的核心-->    <script type="text/javascript" src="${resource(dir: 'js', file: 'highcharts/highcharts.js')}"></script>   <!--导出图片用的-->   <script type="text/javascript" src="${resource(dir: 'js', file: 'highcharts/modules/exporting.js')}"></script>   <!--主题-->   <script type="text/javascript" src="${resource(dir: 'js', file: 'highcharts/themes/gray.js')}"></script>    <script type="text/javascript">       $(function() {       Highcharts.setOptions({         global: {           useUTC: false         }       });        //声明报表对象        chart = new Highcharts.Chart({         chart: {           renderTo: 'container',           defaultSeriesType: 'spline',           marginRight: 10         },         title: {           text: 'CPU使用率动态曲线图'         },         xAxis: {           title: {             text: '时间'           },           //linear" or "datetime"           type: 'datetime',           //坐标间隔           tickPixelInterval: 150         },         yAxis: {           title: {             text: '使用率'           },           //指定y=3直线的样式           plotLines: [             {               value: 0,               width: 10,               color: '#808080'             }           ]         },         //鼠标放在某个点上时的提示信息         //dateFormat,numberFormat是highCharts的工具类         tooltip: {           formatter: function() {             return '<b>' + this.series.name + '</b><br/>' +                     Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +                     Highcharts.numberFormat(this.y, 2);           }         },         //曲线的示例说明,像地图上得图标说明一样         legend: {           enabled: true         },         //把曲线图导出成图片等格式         exporting: {           enabled: true         },         //放入数据         series: [           {             name: 'CPU使用率',             data: (function() {               // 初始化数据               var data = [],                       time = (new Date()).getTime(),                       i;               for (i = -19; i <= 0; i++) {                 data.push({                   x: time + i * 1000,                   y: Math.random() * 100                 });               }               return data;             })()           }         ]       });       getCpuInfo();     });      function getCpuInfo() {       $.post("${createLink(controller:'cpuMonitor',action:'getCpuInfo')}", {"random":Math.random()}, function(data) {         var result = {"x":data.x,"y":data.y};          var series = chart.series[0];         var x = result.x; // current time         var y = result.y;         series.addPoint([x, y], true, true);       }, "json");     }     setInterval(getCpuInfo, 1000);    </script>  </head> <body> <div style="width:800px;height:400px;overflow:auto;">   <div id="container" style="width:800px;height:400px;margin:0 auto;"></div> </div> </body> </html></pre>    <p><span style="font-size:medium;">5、漂亮的效果图:</span> </p>    <p><br /> <img style="width:688px;height:359px;" title="d2f4dfe9-8c8d-3dde-b40d-050ac2781107.png" border="0" alt="d2f4dfe9-8c8d-3dde-b40d-050ac2781107.png" src="https://simg.open-open.com/show/113b72fb93b9d4687cca0eefddde77fd.png" /></p>    <p><span style="font-size:medium;">6、我的dll库文件在下面,欢迎大家下载使用</span></p>    <p></p>    <p></p>    <div class="attachments">     <ul style="display:none;">      <li><a href="https://simg.open-open.com/show/113b72fb93b9d4687cca0eefddde77fd.png" target="_blank"><img class="magplus" title="点击查看原始大小图片" src="https://simg.open-open.com/show/6aef4c1083614ecfeb51d4c40d820233.png" /></a></li>      <li>大小: 38 KB</li>     </ul>     <ul>      <li><a href="/misc/goto?guid=4959500600296443548">DllTest.zip</a> (11.8 KB)</li>     </ul>    </div> 转自:    <a href="/misc/goto?guid=4959500600380634693" target="_blank">http://ligson.iteye.com/blog/1340433</a>