因此,我正在尝试编写一个Java函数,该函数收集进程的CPU时间,并将它们与之前的读数进行比较,以确定自上次采样以来进程所需的CPU时间。我发现了如何从这个网站获取进程的CPU时间http://codeseekah.com/2012/10/21/android-shell-tricks-ps/
基本上,您可以执行"ps-x"并添加您在末尾看到的值;它们看起来是这样的(u:15,s:854)。问题是,我得到的价值似乎比预期的要高。我在这里理解这一页的方式http://en.wikipedia.org/wiki/CPU_time#Total_CPU_time,是给定壁时间间隔中的最大CPU时间是(核的数量)*(壁时间间隔)。我的测试设备有4个核心,我每3秒采样一次。我从当前值中减去以前的值,经常看到超过12秒的最终值。这可能吗?我是不是误解了数据?我会在下面发布一些代码片段
if (currentNameAndTime.get(i).processName.equals(oldNameAndTime.get(j).processName)) {
// If they match, subtract the CPU times, and store the
// result in the time field
obj.time = (currentNameAndTime.get(i).time - oldNameAndTime.get(j).time);
// Add the object to the array that will be returned
finalNameAndTime.add(obj);
// Break the chain, as after a match is found, all other
// name comparisons will fail
break;
}
if (oldNameAndTime.size() == 0) {
FgBgCPUInfo obj = new FgBgCPUInfo();
obj.processName = "FIRST RUN";
obj.time = 0;
finalNameAndTime.add(obj);
}
oldNameAndTime = new ArrayList<FgBgCPUInfo>(currentNameAndTime);
谢谢!
这些值是以时钟为单位的CPU和系统时间。定义可以在桌面系统的man 5 proc
文本中找到:
utime %lu Amount of time that this process has been scheduled
in user mode, measured in clock ticks (divide by
sysconf(_SC_CLK_TCK). This includes guest time,
guest_time (time spent running a virtual CPU, see
below), so that applications that are not aware of
the guest time field do not lose that time from
their calculations.
stime %lu Amount of time that this process has been scheduled
in kernel mode, measured in clock ticks (divide by
sysconf(_SC_CLK_TCK).
这些值是按线程跟踪的,因此您应该使用ps -t -x
来查看每个进程中的所有线程。如果没有-t
,你只需要查看主线程的统计数据,这可能就是为什么你的数字加起来不起来的原因。