001/** 002 * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ 003 * 004 * This file is part of Dicoogle/dicoogle. 005 * 006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * Dicoogle/dicoogle is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with Dicoogle. If not, see <http://www.gnu.org/licenses/>. 018 */ 019package pt.ua.dicoogle.utils; 020 021import java.lang.management.ManagementFactory; 022import java.lang.management.OperatingSystemMXBean; 023import java.lang.management.ThreadMXBean; 024import java.util.Date; 025 026/** 027 * 028 * @author Luís A. Bastião Silva <bastiao@ua.pt> 029 */ 030public class CPULoad 031{ 032 033 034 public CPULoad() 035 { 036 037 } 038 039 public double cpuLoad() 040 { 041 042 ThreadMXBean TMB = ManagementFactory.getThreadMXBean(); 043 long time = new Date().getTime() * 1000000; 044 long cput = 0; 045 double cpuperc = -1; 046 047 //Begin loop. 048 049 if( TMB.isThreadCpuTimeSupported() ) 050 { 051 if(new Date().getTime() * 1000000 - time > 1000000000) //Reset once per second 052 { 053 time = new Date().getTime() * 1000000; 054 cput = TMB.getCurrentThreadCpuTime(); 055 } 056 057 if(!TMB.isThreadCpuTimeEnabled()) 058 { 059 TMB.setThreadCpuTimeEnabled(true); 060 } 061 062 if(new Date().getTime() * 1000000 - time != 0) 063 cpuperc = (TMB.getCurrentThreadCpuTime() - cput) / (new Date().getTime() * 1000000.0 - time) * 100.0; 064 } 065 else 066 { 067 cpuperc = -2; 068 } 069 070 return cpuperc; 071 072 } 073 074 public static double getAvgCpu() 075 { 076 OperatingSystemMXBean osBean=ManagementFactory.getOperatingSystemMXBean(); 077 return osBean.getSystemLoadAverage(); 078 } 079 080 081 082 083 084 085 086 087} 088