CpuInfo.java 7.1 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
/**
 * operate CPU information
 * 
A
andrewleo 已提交
36
 * @author andrewleo
37
 */
K
kevinkong 已提交
38 39
public class CpuInfo {

A
andrewleo 已提交
40
	private static final String LOG_TAG = "Emmagee-" + CpuInfo.class.getSimpleName();
K
kevinkong 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53

	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
	 * 
	 * @throws FileNotFoundException
	 */
	public void readCpuStat() {
		String processPid = Integer.toString(pid);
		String cpuStatPath = "/proc/" + processPid + "/stat";
		try {
			// monitor cpu stat of certain process
A
andrewleo 已提交
82
			RandomAccessFile processCpuInfo = new RandomAccessFile(cpuStatPath, "r");
K
kevinkong 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
			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 已提交
102 103
			String[] toks = cpuInfo.readLine().split("\\s+");
			idleCpu = Long.parseLong(toks[4]);
A
andrewleo 已提交
104 105
			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 已提交
106 107 108 109 110 111 112 113 114
			cpuInfo.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

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

	/**
132
	 * reserve used ratio of process CPU and total CPU, meanwhile collect
A
andrewleo2013 已提交
133
	 * network traffic.
K
kevinkong 已提交
134
	 * 
135 136
	 * @return network traffic ,used ratio of process CPU and total CPU in
	 *         certain interval
K
kevinkong 已提交
137
	 */
A
andrewleo 已提交
138
	public ArrayList<String> getCpuRatioInfo(String totalBatt, String currentBatt, String temperature, String voltage) {
K
kevinkong 已提交
139 140

		DecimalFormat fomart = new DecimalFormat();
A
andrewleo 已提交
141
		// fomart.setGroupingUsed(false);
K
kevinkong 已提交
142 143 144 145
		fomart.setMaximumFractionDigits(2);
		fomart.setMinimumFractionDigits(2);

		readCpuStat();
146
		cpuUsedRatio.clear();
K
kevinkong 已提交
147 148

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

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

180
				if (isPositive(processCpuRatio) && isPositive(totalCpuRatio)) {
A
andrewleo 已提交
181
					// whether certain device supports traffic statics or not
182
					if (traffic == -1) {
A
andrewleo 已提交
183
						EmmageeService.bw.write(mDateTime2 + "," + pMemory + "," + percent + "," + fMemory + "," + processCpuRatio + ","
184
								+ totalCpuRatio + "," + "N/A" + "," + totalBatt + "," + currentBatt + "," + temperature + "," + voltage + "\r\n");
A
andrewleo 已提交
185 186 187 188 189 190 191 192 193 194
					} else {
						EmmageeService.bw.write(mDateTime2 + "," + pMemory + "," + percent + "," + fMemory + "," + processCpuRatio + ","
								+ totalCpuRatio + "," + traffic + "," + totalBatt + "," + currentBatt + "," + temperature + "," + voltage + "\r\n");
					}
					totalCpu2 = totalCpu;
					processCpu2 = processCpu;
					idleCpu2 = idleCpu;
					cpuUsedRatio.add(processCpuRatio);
					cpuUsedRatio.add(totalCpuRatio);
					cpuUsedRatio.add(String.valueOf(traffic));
K
kevinkong 已提交
195 196 197 198 199
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
200
		return cpuUsedRatio;
K
kevinkong 已提交
201
	}
A
andrewleo 已提交
202 203

	/**
204
	 * is text a positive number
A
andrewleo 已提交
205 206 207 208
	 * 
	 * @param text
	 * @return
	 */
209 210
	private boolean isPositive(String text) {
		Double num;
A
andrewleo 已提交
211
		try {
212
			num = Double.parseDouble(text);
A
andrewleo 已提交
213 214 215
		} catch (NumberFormatException e) {
			return false;
		}
216
		return num >= 0;
A
andrewleo 已提交
217 218
	}

K
kevinkong 已提交
219
}