0

So I'm trying to write a Java function that gathers CPU time for processes, and compares them to prior readings to determine the CPU time a process has demanded since the last sample was taken. I found out how to get the CPU time of processes from this site http://codeseekah.com/2012/10/21/android-shell-tricks-ps/

Basically, you can execute "ps -x" and add the values you see at the end; they look like this (u:15, s:854). The problem is that I seem to be getting higher values than expected. The way I understand this page here http://en.wikipedia.org/wiki/CPU_time#Total_CPU_time, is that the maximum CPU time in a given wall time interval is (number of cores)*(wall time interval). My testing device has 4 cores, and I am sampling every 3 seconds. I subtract previous from current values, and often see final values that are above 12 seconds. Is that possible? Am I misinterpreting the data? I'll post some code snippets below

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);

Thank you!

4

1 回答 1

1

这些值是以时钟滴答为单位的 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如果您只是查看主线程的统计信息,这可能就是您的数字不加起来的原因。

于 2014-02-14T00:57:04.887 回答