1 // Copyright (c) 2013 Intel Corporation. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.xwalk.core.internal.extension.api.device_capabilities;
7 import android.util.Log;
9 import java.io.RandomAccessFile;
10 import java.io.IOException;
12 import org.json.JSONException;
13 import org.json.JSONObject;
15 class DeviceCapabilitiesCPU {
16 private static final String SYSTEM_INFO_STAT_FILE = "/proc/stat";
17 private static final String TAG = "DeviceCapabilitiesCPU";
19 private DeviceCapabilities mDeviceCapabilities;
21 private int mCoreNum = 0;
22 private String mCPUArch = "Unknown";
23 private double mCPULoad = 0.0;
25 public DeviceCapabilitiesCPU(DeviceCapabilities instance) {
26 mDeviceCapabilities = instance;
28 // Get arch and core number at constructor since they won't change time to time.
29 mCoreNum = Runtime.getRuntime().availableProcessors();
30 mCPUArch = System.getProperty("os.arch");
33 public JSONObject getInfo() {
36 JSONObject out = new JSONObject();
38 out.put("numOfProcessors", mCoreNum);
39 out.put("archName", mCPUArch);
40 out.put("load", mCPULoad);
41 } catch (JSONException e) {
42 return mDeviceCapabilities.setErrorMessage(e.toString());
49 * The algorithm here can be found at:
50 * http://stackoverflow.com/questions/3017162/how-to-get-total-cpu-usage-in-linux-c
52 private boolean getCPULoad() {
54 RandomAccessFile file = new RandomAccessFile(SYSTEM_INFO_STAT_FILE, "r");
55 String line = file.readLine();
57 String[] arrs = line.split("\\s+");
59 for (int i = 1; i < arrs.length; ++i) {
60 total1 += Long.parseLong(arrs[i]);
62 // arrs[4] is the time spent in idle tasks.
63 long used1 = total1 - Long.parseLong(arrs[4]);
66 } catch (Exception e) {
72 line = file.readLine();
75 arrs = line.split("\\s+");
77 for (int i = 1; i < arrs.length; ++i) {
78 total2 += Long.parseLong(arrs[i]);
80 // arrs[4] is the time spent in idle tasks.
81 long used2 = total2 - Long.parseLong(arrs[4]);
82 if (total2 == total1) {
85 mCPULoad = (double) (used2 - used1) / (total2 - total1);
87 } catch (IOException e) {