whyclj
2020-08-29 166f2f34ffed7ee9562eff02482ac6a3f7168bcd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main;
 
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
 
public class ComputerMonitorUtil {
        private static String osName = System.getProperty("os.name");
        private static final int CPUTIME = 500;
        private static final int PERCENT = 100;
        private static final int FAULTLENGTH = 10;
 
        /**
        * ¹¦ÄÜ£º»ñÈ¡LinuxºÍWindowϵͳcpuʹÓÃÂÊ
        * */
        public static double getCpuUsage() {
        // Èç¹ûÊÇwindowϵͳ
        if (osName.toLowerCase().contains("windows")
                || osName.toLowerCase().contains("win")) {
            try {
                String procCmd = System.getenv("windir")
                + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
                // È¡½ø³ÌÐÅÏ¢
                long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));//µÚÒ»´Î¶ÁÈ¡CPUÐÅÏ¢
                Thread.sleep(CPUTIME);//˯500ms
                long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));//µÚ¶þ´Î¶ÁÈ¡CPUÐÅÏ¢
                if (c0 != null && c1 != null) {
                    long idletime = c1[0] - c0[0];//¿ÕÏÐʱ¼ä
                    long busytime = c1[1] - c0[1];//ʹÓÃʱ¼ä
                    Double cpusage = Double.valueOf(PERCENT * (busytime) * 1.0 / (busytime + idletime));
                    BigDecimal b1 = new BigDecimal(cpusage);
                    double cpuUsage = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    return cpuUsage;
                } else {
                    return 0.0;
                } 
            } catch (Exception ex) {
                ex.printStackTrace();
                return 0.0;
            } 
        } else {
            try {
                Map<?, ?> map1 = ComputerMonitorUtil.cpuinfo();
                Thread.sleep(CPUTIME);
                Map<?, ?> map2 = ComputerMonitorUtil.cpuinfo();
        
                long user1 = Long.parseLong(map1.get("user").toString());
                long nice1 = Long.parseLong(map1.get("nice").toString());
                long system1 = Long.parseLong(map1.get("system").toString());
                long idle1 = Long.parseLong(map1.get("idle").toString());
        
                long user2 = Long.parseLong(map2.get("user").toString());
                long nice2 = Long.parseLong(map2.get("nice").toString());
                long system2 = Long.parseLong(map2.get("system").toString());
                long idle2 = Long.parseLong(map2.get("idle").toString());
        
                long total1 = user1 + system1 + nice1;
                long total2 = user2 + system2 + nice2;
                float total = total2 - total1;
        
                long totalIdle1 = user1 + nice1 + system1 + idle1;
                long totalIdle2 = user2 + nice2 + system2 + idle2;
                float totalidle = totalIdle2 - totalIdle1;
        
                float cpusage = (total / totalidle) * 100;
        
                BigDecimal b1 = new BigDecimal(cpusage);
                double cpuUsage = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                return cpuUsage;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return 0;
        }
 
        /**
        * ¹¦ÄÜ£ºLinux CPUʹÓÃÐÅÏ¢
        * */
        public static Map<?, ?> cpuinfo() {
        InputStreamReader inputs = null;
        BufferedReader buffer = null;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
        inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
        buffer = new BufferedReader(inputs);
        String line = "";
        while (true) {
        line = buffer.readLine();
        if (line == null) {
        break;
        }
        if (line.startsWith("cpu")) {
        StringTokenizer tokenizer = new StringTokenizer(line);
        List<String> temp = new ArrayList<String>();
        while (tokenizer.hasMoreElements()) {
        String value = tokenizer.nextToken();
        temp.add(value);
        }
        map.put("user", temp.get(1));
        map.put("nice", temp.get(2));
        map.put("system", temp.get(3));
        map.put("idle", temp.get(4));
        map.put("iowait", temp.get(5));
        map.put("irq", temp.get(6));
        map.put("softirq", temp.get(7));
        map.put("stealstolen", temp.get(8));
        break;
        }
        }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        try {
        buffer.close();
        inputs.close();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        }
        return map;
        }
 
        // window¶ÁÈ¡cpuÏà¹ØÐÅÏ¢
        private static long[] readCpu(final Process proc) {
        long[] retn = new long[2];
        try {
        proc.getOutputStream().close();
        InputStreamReader ir = new InputStreamReader(proc.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line = input.readLine();
        if (line == null || line.length() < FAULTLENGTH) {
        return null;
        }
        int capidx = line.indexOf("Caption");
        int cmdidx = line.indexOf("CommandLine");
        int rocidx = line.indexOf("ReadOperationCount");
        int umtidx = line.indexOf("UserModeTime");
        int kmtidx = line.indexOf("KernelModeTime");
        int wocidx = line.indexOf("WriteOperationCount");
        long idletime = 0;
        long kneltime = 0;//¶ÁÈ¡ÎïÀíÉ豸ʱ¼ä
        long usertime = 0;//Ö´ÐдúÂëÕ¼ÓÃʱ¼ä
        while ((line = input.readLine()) != null) {
        if (line.length() < wocidx) {
        continue;
        }
        // ×ֶγöÏÖ˳Ðò£ºCaption,CommandLine,KernelModeTime,ReadOperationCount
        String caption = substring(line, capidx, cmdidx - 1).trim();
//            System.out.println("caption:"+caption);
        String cmd = substring(line, cmdidx, kmtidx - 1).trim();
//            System.out.println("cmd:"+cmd);
        if (cmd.indexOf("wmic.exe") >= 0) {
        continue;
        }
        String s1 = substring(line, kmtidx, rocidx - 1).trim();
        String s2 = substring(line, umtidx, wocidx - 1).trim();
        List<String> digitS1 = getDigit(s1);
        List<String> digitS2 = getDigit(s2);
 
//            System.out.println("s1:"+digitS1.get(0));
//            System.out.println("s2:"+digitS2.get(0));
 
        if (caption.equals("System Idle Process") || caption.equals("System")) {
        if (s1.length() > 0) {
        if (!digitS1.get(0).equals("") && digitS1.get(0) != null) {
        idletime += Long.valueOf(digitS1.get(0)).longValue();
        }
        }
        if (s2.length() > 0) {
        if (!digitS2.get(0).equals("") && digitS2.get(0) != null) {
        idletime += Long.valueOf(digitS2.get(0)).longValue();
        }
        }
        continue;
        }
        if (s1.length() > 0) {
        if (!digitS1.get(0).equals("") && digitS1.get(0) != null) {
        kneltime += Long.valueOf(digitS1.get(0)).longValue();
        }
        }
 
        if (s2.length() > 0) {
        if (!digitS2.get(0).equals("") && digitS2.get(0) != null) {
        kneltime += Long.valueOf(digitS2.get(0)).longValue();
        }
        }
        }
        retn[0] = idletime;
        retn[1] = kneltime + usertime;
 
        return retn;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        try {
        proc.getInputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
        return null;
        }
 
        /**
        * ´Ó×Ö·û´®Îı¾ÖлñµÃÊý×Ö
        * 
        * @param text
        * @return
        */
        private static List<String> getDigit(String text) {
        List<String> digitList = new ArrayList<String>();
        digitList.add(text.replaceAll("\\D", ""));
        return digitList;
        }
 
        /**
        * ÓÉÓÚString.subString¶Ôºº×Ö´¦Àí´æÔÚÎÊÌ⣨°ÑÒ»¸öºº×ÖÊÓΪһ¸ö×Ö½Ú)£¬Òò´ËÔÚ °üº¬ºº×ÖµÄ×Ö·û´®Ê±´æÔÚÒþ»¼£¬ÏÖµ÷ÕûÈçÏ£º
        * 
        * @param src
        * Òª½ØÈ¡µÄ×Ö·û´®
        * @param start_idx
        * ¿ªÊ¼×ø±ê£¨°üÀ¨¸Ã×ø±ê)
        * @param end_idx
        * ½ØÖ¹×ø±ê£¨°üÀ¨¸Ã×ø±ê£©
        * @return
        */
        private static String substring(String src, int start_idx, int end_idx) {
        byte[] b = src.getBytes();
        String tgt = "";
        for (int i = start_idx; i <= end_idx; i++) {
        tgt += (char) b[i];
        }
        return tgt;
        }
    /*
    public static void main(String[] args) throws Exception {
 
        double cpuUsage = ComputerMonitorUtil.getCpuUsage();
 
        System.out.println("cpuUsage:"+cpuUsage);
    }
    */
}