Android采集代码:
public static float totalCpuUsageRate() {
return getTotalCpuUsageRate(USAGE_RATE_CAL_INTERVAL_MILLS_DEFAULT);
}
public static float getTotalCpuUsageRate(long calIntervalMills) {
if (0 > calIntervalMills) {
return VALUE_GET_FAILED;
}
float totalCpuUsageRate = VALUE_GET_FAILED;
try {
TotalCpuStatInfo totalCpuStatInfo1 = TotalCpuStatInfo.get();
long cpuTotal1 = totalCpuStatInfo1.getCpuTotal();
if (0 > cpuTotal1) {
return totalCpuUsageRate;
}
long total1 = totalCpuStatInfo1.getTotal();
if (0 > total1) {
return totalCpuUsageRate;
}
try {
Thread.sleep(calIntervalMills);
} catch (Exception e) {
GPMLogger.w(e, "getTotalCpuUsageRate failed");
}
TotalCpuStatInfo totalCpuStatInfo2 = TotalCpuStatInfo.get();
long cpuTotal2 = totalCpuStatInfo2.getCpuTotal();
if (0 > cpuTotal2) {
return totalCpuUsageRate;
}
long total2 = totalCpuStatInfo2.getTotal();
if (0 > total2) {
return totalCpuUsageRate;
}
long totalDiff = total2 - total1;
if (0 == totalDiff) {
// NOTE: totalDiff为分母
return totalCpuUsageRate;
}
long cpuTotalDiff = cpuTotal2 - cpuTotal1;
return 100 * cpuTotalDiff / (totalDiff + 0f);
} catch (Exception e) {
GPMLogger.w(e, "getTotalCpuUsageRate failed");
}
return totalCpuUsageRate;
}
public static float myCpuUsageRate() {
return getMyCpuUsageRate(USAGE_RATE_CAL_INTERVAL_MILLS_DEFAULT);
}
public static float getMyCpuUsageRate(long calIntervalMills) {
if (0 > calIntervalMills) {
return VALUE_GET_FAILED;
}
float myCpuUsageRate = VALUE_GET_FAILED;
try {
TotalCpuStatInfo totalCpuStatInfo1 = TotalCpuStatInfo.get();
long total1 = totalCpuStatInfo1.getTotal();
if (0 > total1) {
return myCpuUsageRate;
}
MyCpuStatInfo myCpuStatInfo1 = MyCpuStatInfo.get();
long myCpuTotal1 = myCpuStatInfo1.getCpuTotal();
if (0 > myCpuTotal1) {
return myCpuUsageRate;
}
try {
Thread.sleep(calIntervalMills);
} catch (Exception e) {
GPMLogger.w(e, "getMyCpuUsageRate failed");
}
TotalCpuStatInfo totalCpuStatInfo2 = TotalCpuStatInfo.get();
long total2 = totalCpuStatInfo2.getTotal();
if (0 > total2) {
return myCpuUsageRate;
}
MyCpuStatInfo myCpuStatInfo2 = MyCpuStatInfo.get();
long myCpuTotal2 = myCpuStatInfo2.getCpuTotal();
if (0 > myCpuTotal2) {
return myCpuUsageRate;
}
long totalDiff = total2 - total1;
if (0 == totalDiff) {
// NOTE: totalDiff为分母
return myCpuUsageRate;
}
long myCpuTotalDiff = myCpuTotal2 - myCpuTotal1;
return 100 * myCpuTotalDiff / (totalDiff + 0f);
} catch (Exception e) {
GPMLogger.w(e, "getTotalCpuUsageRate failed");
}
return myCpuUsageRate;
}
private static class TotalCpuStatInfo {
private static final int MIN_CPU_STAT_ITEM_NUM = 9;
private static final String[] INVALID_RAW_CPU_STAT_ITEMS =
new String[MIN_CPU_STAT_ITEM_NUM];
public final long user;
public final long nice;
public final long system;
public final long idle;
public final long iowait;
public final long irq;
public final long softirq;
public static TotalCpuStatInfo get() {
BufferedReader cpuStatInfoReader = null;
try {
cpuStatInfoReader = new BufferedReader(new InputStreamReader(new FileInputStream(STAT_ABS_DIR), UTF8_CHARSET));
return new TotalCpuStatInfo(cpuStatInfoReader.readLine());
} catch (Exception e) {
// NOTE: 高版本上获取不到, 不打印堆栈
GPMLogger.d("get total cpu stat info failed");
return new TotalCpuStatInfo(null);
} finally {
if (null != cpuStatInfoReader) {
try {
cpuStatInfoReader.close();
} catch (IOException ignored) {
}
}
}
}
private TotalCpuStatInfo(String cpuStatLine) {
String[] rawCpuStatItems = CpuStatInfoHelper.buildRawCpuStatItems(cpuStatLine, MIN_CPU_STAT_ITEM_NUM, INVALID_RAW_CPU_STAT_ITEMS);
user = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[2]);
nice = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[3]);
system = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[4]);
idle = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[5]);
iowait = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[6]);
irq = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[7]);
softirq = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[8]);
}
public long getCpuTotal() {
return user + nice + system + iowait + irq + softirq;
}
public long getTotal() {
return user + nice + system + idle + iowait + irq + softirq;
}
}
private static class MyCpuStatInfo {
private static final int MIN_CPU_STAT_ITEM_NUM = 17;
private static final String[] INVALID_RAW_CPU_STAT_ITEMS = new String[MIN_CPU_STAT_ITEM_NUM];
public final long utime;
public final long stime;
public final long cutime;
public final long cstime;
public static MyCpuStatInfo get() {
BufferedReader cpuStatInfoReader = null;
try {
cpuStatInfoReader = new BufferedReader(new InputStreamReader(new FileInputStream(MY_STAT_ABS_DIR), UTF8_CHARSET));
return new MyCpuStatInfo(cpuStatInfoReader.readLine());
} catch (Exception e) {
GPMLogger.w(e, "get my cpu stat info failed");
return new MyCpuStatInfo(null);
} finally {
if (null != cpuStatInfoReader) {
try {
cpuStatInfoReader.close();
} catch (IOException ignored) {
}
}
}
}
private MyCpuStatInfo(String cpuStatLine) {
String[] rawCpuStatItems = CpuStatInfoHelper.buildRawCpuStatItems(cpuStatLine, MIN_CPU_STAT_ITEM_NUM, INVALID_RAW_CPU_STAT_ITEMS);
utime = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[13]);
stime = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[14]);
cutime = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[15]);
cstime = CpuStatInfoHelper.buildCpuStatItem(rawCpuStatItems[16]);
}
public long getCurrentThreadCpuTotal() {
return utime + stime;
}
public long getCpuTotal() {
return utime + stime + cutime + cstime;
}
}
IOS采集代码:
// ============当前进程cpu使用率============
- (double) getCPU {
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
GSDKLOG(@"================CPU:%.2f",-1.0f);
return -1;
}
task_basic_info_t basic_info;
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
uint32_t stat_thread = 0; // Mach threads
basic_info = (task_basic_info_t)tinfo;
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
GSDKLOG(@"=============CPU:%.2f",-1.0f);
return -1;
}
if (thread_count > 0)
stat_thread += thread_count;
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < thread_count; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO, (thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
GSDKLOG(@"=========CPU:%.2f",-1.0f);
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
}
} // for each thread
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
GSDKLOG(@"=============CPU:%.2f",tot_cpu);
return tot_cpu;
}
// ============当前进程cpu使用率============
processor_info_array_t cpuInfo, prevCpuInfo;
mach_msg_type_number_t numCpuInfo, numPrevCpuInfo;
unsigned numCPUs;
NSLock * CPUUsageLock;
- (void) getSystemCPU {
int mib[2U] = { CTL_HW, HW_NCPU };
size_t sizeOfNumCPUs = sizeof(numCPUs);
int status = sysctl(mib, 2U, &numCPUs, &sizeOfNumCPUs, NULL, 0U);
if (status)
numCPUs = 1;
CPUUsageLock = [[NSLock alloc] init];
}
- (double) getSystemCPUCircle {
natural_t numCPUsU = 0U;
kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUsU, &cpuInfo, &numCpuInfo);
if (err == KERN_SUCCESS) {
[CPUUsageLock lock];
float tot_inUse = 0;
float tot_total = 0;
for(unsigned i = 0U; i < numCPUs; ++i) {
float inUse, total;
if(prevCpuInfo) {
inUse = ((cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
+ (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
+ (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]));
total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
} else {
inUse = cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
}
tot_inUse += inUse;
tot_total += total;
}
[CPUUsageLock unlock];
if (prevCpuInfo) {
size_t prevCpuInfoSize = sizeof(integer_t) * numPrevCpuInfo;
vm_deallocate(mach_task_self(), (vm_address_t)prevCpuInfo, prevCpuInfoSize);
}
prevCpuInfo = cpuInfo;
numPrevCpuInfo = numCpuInfo;
cpuInfo = NULL;
numCpuInfo = 0U;
if (tot_total > 0) {
GSDKLOG(@"CPU Usage: %.2f%%",tot_inUse/tot_total * 100.f);
return tot_inUse/tot_total * 100.f;
} else {
return -1;
}
} else {
GSDKLOG(@"Error!");
return -1;
}
}