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;
14 import org.xwalk.core.internal.extension.XWalkExtensionContext;
16 class DeviceCapabilitiesCPU {
17 private static final String SYSTEM_INFO_STAT_FILE = "/proc/stat";
18 private static final String TAG = "DeviceCapabilitiesCPU";
20 private DeviceCapabilities mDeviceCapabilities;
22 private int mCoreNum = 0;
23 private String mCPUArch = "Unknown";
24 private double mCPULoad = 0.0;
26 public DeviceCapabilitiesCPU(DeviceCapabilities instance,
27 XWalkExtensionContext context) {
28 mDeviceCapabilities = instance;
30 // Get arch and core number at constructor since they won't change time to time.
31 mCoreNum = Runtime.getRuntime().availableProcessors();
32 mCPUArch = System.getProperty("os.arch");
35 public JSONObject getInfo() {
38 JSONObject out = new JSONObject();
40 out.put("numOfProcessors", mCoreNum);
41 out.put("archName", mCPUArch);
42 out.put("load", mCPULoad);
43 } catch (JSONException e) {
44 return mDeviceCapabilities.setErrorMessage(e.toString());
51 * The algorithm here can be found at:
52 * http://stackoverflow.com/questions/3017162/how-to-get-total-cpu-usage-in-linux-c
54 private boolean getCPULoad() {
56 RandomAccessFile file = new RandomAccessFile(SYSTEM_INFO_STAT_FILE, "r");
57 String line = file.readLine();
59 String[] arrs = line.split("\\s+");
61 for (int i = 1; i < arrs.length; ++i) {
62 total1 += Long.parseLong(arrs[i]);
64 // arrs[4] is the time spent in idle tasks.
65 long used1 = total1 - Long.parseLong(arrs[4]);
68 } catch (Exception e) {
74 line = file.readLine();
77 arrs = line.split("\\s+");
79 for (int i = 1; i < arrs.length; ++i) {
80 total2 += Long.parseLong(arrs[i]);
82 // arrs[4] is the time spent in idle tasks.
83 long used2 = total2 - Long.parseLong(arrs[4]);
84 if (total2 == total1) {
87 mCPULoad = (double) (used2 - used1) / (total2 - total1);
89 } catch (IOException e) {