Highcharts動態曲線圖(使用jna監視cpu使用率)

fmms 12年前發布 | 54K 次閱讀 Java開發 Highcharts

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 <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>

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];
}

}</pre>

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);

} }</pre>

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" %> <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>

5、漂亮的效果圖:


d2f4dfe9-8c8d-3dde-b40d-050ac2781107.png

6、我的dll庫文件在下面,歡迎大家下載使用

  • 大小: 38 KB
轉自: http://ligson.iteye.com/blog/1340433

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!