CpuInfo.java 10.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2012-2013 NetEase, Inc. and other contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
K
kevinkong 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29
package com.netease.qa.emmagee.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import com.netease.qa.emmagee.service.EmmageeService;

import android.content.Context;
A
andrewleo2013 已提交
30
import android.os.Build;
K
kevinkong 已提交
31 32
import android.util.Log;

33 34 35 36
/**
 * operate CPU information
 * 
 */
K
kevinkong 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
public class CpuInfo {

	private static final String LOG_TAG = "Emmagee-"
			+ CpuInfo.class.getSimpleName();

	private Context context;
	private long processCpu;
	private long idleCpu;
	private long totalCpu;
	private boolean isInitialStatics = true;
	private SimpleDateFormat formatterFile;
	private MemoryInfo mi;
	private long totalMemorySize;
	private long initialTraffic;
	private long lastestTraffic;
	private long traffic;
	private TrafficInfo trafficInfo;
54
	private ArrayList<String> cpuUsedRatio;
K
kevinkong 已提交
55 56 57 58 59 60 61
	private long totalCpu2;
	private long processCpu2;
	private long idleCpu2;
	private String processCpuRatio = "";
	private String totalCpuRatio = "";
	private int pid;

A
andrewleo 已提交
62
	public CpuInfo(Context context, int pid, String uid) {
K
kevinkong 已提交
63 64 65 66 67 68
		this.pid = pid;
		this.context = context;
		trafficInfo = new TrafficInfo(uid);
		formatterFile = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mi = new MemoryInfo();
		totalMemorySize = mi.getTotalMemory();
69
		cpuUsedRatio = new ArrayList<String>();
K
kevinkong 已提交
70 71 72
	}

	/**
A
andrewleo2013 已提交
73
	 * read the status of CPU.
K
kevinkong 已提交
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
	 * 
	 * @throws FileNotFoundException
	 */
	public void readCpuStat() {
		String processPid = Integer.toString(pid);
		String cpuStatPath = "/proc/" + processPid + "/stat";
		try {
			// monitor cpu stat of certain process
			RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath,
					"r");
			String line = "";
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.setLength(0);
			while ((line = processCpuInfo.readLine()) != null) {
				stringBuffer.append(line + "\n");
			}
			String[] tok = stringBuffer.toString().split(" ");
			processCpu = Long.parseLong(tok[13]) + Long.parseLong(tok[14]);
			processCpuInfo.close();
		} catch (FileNotFoundException e) {
			Log.e(LOG_TAG, "FileNotFoundException: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			// monitor total and idle cpu stat of certain process
			RandomAccessFile cpuInfo = new RandomAccessFile("/proc/stat", "r");
A
andrewleo2013 已提交
103 104 105 106 107 108
			String[] toks = cpuInfo.readLine().split("\\s+");
			idleCpu = Long.parseLong(toks[4]);
			totalCpu = Long.parseLong(toks[1]) + Long.parseLong(toks[2])
					+ Long.parseLong(toks[3]) + Long.parseLong(toks[4])
					+ Long.parseLong(toks[6]) + Long.parseLong(toks[5])
					+ Long.parseLong(toks[7]);
K
kevinkong 已提交
109 110 111 112 113 114 115 116 117
			cpuInfo.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
A
andrewleo2013 已提交
118
	 * get CPU name.
K
kevinkong 已提交
119
	 * 
120
	 * @return CPU name
K
kevinkong 已提交
121 122 123
	 */
	public String getCpuName() {
		try {
A
andrewleo2013 已提交
124
			RandomAccessFile cpuStat = new RandomAccessFile("/proc/cpuinfo",
K
kevinkong 已提交
125
					"r");
A
andrewleo2013 已提交
126 127
			String[] cpu = cpuStat.readLine().split(":"); // cpu信息的前一段是含有processor字符串,此处替换为不显示
			cpuStat.close();
K
kevinkong 已提交
128 129 130 131 132 133 134 135
			return cpu[1];
		} catch (IOException e) {
			Log.e(LOG_TAG, "IOException: " + e.getMessage());
		}
		return "";
	}

	/**
136
	 * reserve used ratio of process CPU and total CPU, meanwhile collect
A
andrewleo2013 已提交
137
	 * network traffic.
K
kevinkong 已提交
138
	 * 
139 140
	 * @return network traffic ,used ratio of process CPU and total CPU in
	 *         certain interval
K
kevinkong 已提交
141
	 */
A
andrewleo 已提交
142 143
	public ArrayList<String> getCpuRatioInfo(String totalBatt,
			String currentBatt, String temperature, String voltage) {
K
kevinkong 已提交
144 145 146 147 148 149

		DecimalFormat fomart = new DecimalFormat();
		fomart.setMaximumFractionDigits(2);
		fomart.setMinimumFractionDigits(2);

		readCpuStat();
150
		cpuUsedRatio.clear();
K
kevinkong 已提交
151 152

		try {
A
andrewleo2013 已提交
153
			String mDateTime2;
K
kevinkong 已提交
154
			Calendar cal = Calendar.getInstance();
A
andrewleo2013 已提交
155 156 157 158
			if ((Build.MODEL.equals("sdk"))
					|| (Build.MODEL.equals("google_sdk"))) {
				mDateTime2 = formatterFile.format(cal.getTime().getTime() + 8
						* 60 * 60 * 1000);
A
andrewleo 已提交
159 160 161 162
				totalBatt = "N/A";
				currentBatt = "N/A";
				temperature = "N/A";
				voltage = "N/A";
A
andrewleo2013 已提交
163
			} else
A
andrewleo2013 已提交
164
				mDateTime2 = formatterFile.format(cal.getTime().getTime());
K
kevinkong 已提交
165

A
andrewleo2013 已提交
166
			if (isInitialStatics) {
K
kevinkong 已提交
167 168 169 170 171 172 173 174
				initialTraffic = trafficInfo.getTrafficInfo();
				isInitialStatics = false;
			} else {
				lastestTraffic = trafficInfo.getTrafficInfo();
				if (initialTraffic == -1)
					traffic = -1;
				else
					traffic = (lastestTraffic - initialTraffic + 1023) / 1024;
A
andrewleo 已提交
175 176 177 178
				processCpuRatio = fomart
						.format(100 * ((double) (processCpu - processCpu2) / ((double) (totalCpu - totalCpu2))));
				totalCpuRatio = fomart
						.format(100 * ((double) ((totalCpu - idleCpu) - (totalCpu2 - idleCpu2)) / (double) (totalCpu - totalCpu2)));
A
andrewleo 已提交
179
				long pidMemory = mi.getPidMemorySize(pid, context);
K
kevinkong 已提交
180 181 182 183 184 185 186 187 188
				String pMemory = fomart.format((double) pidMemory / 1024);
				long freeMemory = mi.getFreeMemorySize(context);
				String fMemory = fomart.format((double) freeMemory / 1024);
				String percent = "统计出错";
				if (totalMemorySize != 0) {
					percent = fomart
							.format(((double) pidMemory / (double) totalMemorySize) * 100);
				}

189
				// whether certain device supports traffic statics or not
K
kevinkong 已提交
190 191 192 193
				if (traffic == -1) {
					EmmageeService.bw.write(mDateTime2 + "," + pMemory + ","
							+ percent + "," + fMemory + "," + processCpuRatio
							+ "," + totalCpuRatio + "," + "本程序或本设备不支持流量统计"
A
andrewleo 已提交
194 195
							+ "," + totalBatt + "," + currentBatt + ","
							+ temperature + "," + voltage + "\r\n");
K
kevinkong 已提交
196 197 198
				} else {
					EmmageeService.bw.write(mDateTime2 + "," + pMemory + ","
							+ percent + "," + fMemory + "," + processCpuRatio
A
andrewleo 已提交
199 200 201
							+ "," + totalCpuRatio + "," + traffic + ","
							+ totalBatt + "," + currentBatt + "," + temperature
							+ "," + voltage + "\r\n");
K
kevinkong 已提交
202 203 204 205 206
				}
			}
			totalCpu2 = totalCpu;
			processCpu2 = processCpu;
			idleCpu2 = idleCpu;
207 208 209
			cpuUsedRatio.add(processCpuRatio);
			cpuUsedRatio.add(totalCpuRatio);
			cpuUsedRatio.add(String.valueOf(traffic));
K
kevinkong 已提交
210 211 212 213
		} catch (IOException e) {
			e.printStackTrace();
			// PttService.closeOpenedStream()
		}
214
		return cpuUsedRatio;
K
kevinkong 已提交
215 216 217

	}

A
andrewleo2013 已提交
218
	// // TODO coming soon
K
kevinkong 已提交
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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	// public String cpuinfo() {
	// String sys_info = "";
	// String s;
	// try {
	// RandomAccessFile reader_stat = new RandomAccessFile("/proc/stat",
	// "r");
	// RandomAccessFile reader_info = new RandomAccessFile(
	// "/proc/cpuinfo", "r");
	// sys_info = reader_info.readLine(); // CPU型号
	// String load_info;
	// String cpu_stat = reader_stat.readLine(); // cpu行信息
	// String cpu0_stat = reader_stat.readLine(); // cpu0
	// String cpu1_stat = reader_stat.readLine(); // cpu1
	//
	// String[] tok = cpu_stat.split(" ");
	// String[] tok1 = cpu0_stat.split(" ");
	// String[] tok2 = cpu1_stat.split(" ");
	//
	// // 判断单核
	// if (tok[2].equals(tok1[1])) {
	// long idle_s1 = Long.parseLong(tok[5]);
	// long cpu_s1 = Long.parseLong(tok[2]) + Long.parseLong(tok[3])
	// + Long.parseLong(tok[4]) + Long.parseLong(tok[6])
	// + Long.parseLong(tok[5]) + Long.parseLong(tok[7])
	// + Long.parseLong(tok[8]);
	//
	// try {
	// Thread.sleep(1000);
	//
	// } catch (Exception e) {
	// }
	//
	// reader_stat.seek(0);
	//
	// load_info = reader_stat.readLine();
	//
	// reader_stat.close();
	//
	// tok = load_info.split(" ");
	// long idle_s2 = Long.parseLong(tok[5]);
	//
	// long cpu_s2 = Long.parseLong(tok[2]) + Long.parseLong(tok[3])
	// + Long.parseLong(tok[4]) + Long.parseLong(tok[6])
	// + Long.parseLong(tok[5]) + Long.parseLong(tok[7])
	// + Long.parseLong(tok[8]);
	//
	// return "CPU使用率为:"
	// + (100 * ((cpu_s2 - idle_s2) - (cpu_s1 - idle_s1)) / (cpu_s2 - cpu_s1))
	// + "%";
	//
	// }
	//
	// // 双核情况
	// else if (tok2[0].equals("cpu1")) {
	// // 双核
	// reader_stat = new RandomAccessFile("/proc/stat", "r");
	// long[] idle_d1 = null;
	// long[] cpu_d1 = null;
	// long[] idle_d2 = null;
	// long[] cpu_d2 = null;
	// idle_d1[0] = Long.parseLong(tok1[4]); // cpu0空闲时间
	// cpu_d1[0] = Long.parseLong(tok1[2]) + Long.parseLong(tok1[3])
	// + Long.parseLong(tok1[4]) + Long.parseLong(tok1[6])
	// + Long.parseLong(tok1[5]) + Long.parseLong(tok1[7])
	// + Long.parseLong(tok1[1]); // cpu0非空闲时间
	// idle_d1[1] = Long.parseLong(tok2[4]);
	// cpu_d1[1] = Long.parseLong(tok2[2]) + Long.parseLong(tok2[3])
	// + Long.parseLong(tok2[4]) + Long.parseLong(tok2[6])
	// + Long.parseLong(tok2[5]) + Long.parseLong(tok2[7])
	// + Long.parseLong(tok2[1]);
	//
	// try {
	// Thread.sleep(1000);
	//
	// } catch (Exception e) {
	// }
	//
	// reader_stat.seek(0);
	//
	// cpu_stat = reader_stat.readLine(); // cpu行信息
	// cpu0_stat = reader_stat.readLine(); // cpu0
	// cpu1_stat = reader_stat.readLine();
	//
	// tok1 = cpu0_stat.split(" ");
	// tok2 = cpu1_stat.split(" ");
	//
	// idle_d2[0] = Long.parseLong(tok1[4]); // cpu0空闲时间
	// cpu_d2[0] = Long.parseLong(tok1[2]) + Long.parseLong(tok1[3])
	// + Long.parseLong(tok1[4]) + Long.parseLong(tok1[6])
	// + Long.parseLong(tok1[5]) + Long.parseLong(tok1[7])
	// + Long.parseLong(tok1[1]); // cpu0非空闲时间
	// idle_d2[1] = Long.parseLong(tok2[4]);
	// cpu_d2[1] = Long.parseLong(tok2[2]) + Long.parseLong(tok2[3])
	// + Long.parseLong(tok2[4]) + Long.parseLong(tok2[6])
	// + Long.parseLong(tok2[5]) + Long.parseLong(tok2[7])
	// + Long.parseLong(tok2[1]);
	//
	// reader_stat.close();
	// return "CPU1使用率为:"
	// + (100 * ((cpu_d2[0] - idle_d2[0]) - (cpu_d1[0] - idle_d1[0])) /
	// (cpu_d2[0] - cpu_d1[0]))
	// + "%"
	// + "\n"
	// + "CPU2使用率为:"
	// + (100 * ((cpu_d2[1] - idle_d2[1]) - (cpu_d1[1] - idle_d1[1])) /
	// (cpu_d2[1] - cpu_d1[1]))
	// + "%";
	// }
	// } catch (IOException ex) {
	// Log.e(LOG_TAG, ex.getMessage());
	//
	// }
	// return "0";
	// }
}