Как вычислить использование ЦП процесса PID в Linux от C?

Внутри файла манифеста Android попробуйте добавить следующий атрибут для своей MainActivity:

<activity
            android:name=".MainActivity"
            android:windowSoftInputMode="adjustPan">
...
</activity>

, который делает панораму представлений, когда появляется программная клавиатура, но окно действия не изменяется. Посмотрите, имеет ли это какое-то значение. Если изменение размера будет работать лучше, вместо атрибута "adjustPan" вы можете добавить "adjustResize". Надеюсь, что один из двух сделает трюк за вас.

93
задан Mateusz Piotrowski 18 December 2016 в 01:06
поделиться

5 ответов

You need to parse out the data from /proc//stat. These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
..............................................................................
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

You're probably after utime and/or stime. You'll also need to read the cpu line from /proc/stat, which looks like:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a time_total measure.

Read both utime and stime for the process you're interested in, and read time_total from /proc/stat. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:

user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

Make sense?

144
ответ дан 24 November 2019 в 06:17
поделиться

strace использования, найденный использованием ЦП, должен быть вычислен периодом времени:

# top -b -n 1 -p 3889
top - 16:46:37 up  1:04,  3 users,  load average: 0.00, 0.01, 0.02
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  5594496 total,  5158284 free,   232132 used,   204080 buff/cache
KiB Swap:  3309564 total,  3309564 free,        0 used.  5113756 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 3889 root      20   0  162016   2220   1544 S   0.0  0.0   0:05.77 top
# strace top -b -n 1 -p 3889
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.

nanosleep({0, 150000000}, NULL)         = 0
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.
0
ответ дан 24 November 2019 в 06:17
поделиться

getrusage () может помочь вам определить использование текущего процесса или его дочернего процесса

Обновление: Я не могу вспомнить API. Но все подробности будут в / proc / PID / stat, поэтому, если бы мы могли его проанализировать, мы могли бы получить процент.

EDIT: Поскольку CPU% не просто вычислить, вы можете использовать здесь выборку. Считайте ctime и utime для PID в определенный момент времени и снова прочитайте те же значения через 1 секунду. Найдите разницу и разделите на сто. Вы получите использование этого процесса за последнюю секунду.

(может стать сложнее, если процессоров много)

11
ответ дан 24 November 2019 в 06:17
поделиться

Вы можете прочитать справочную страницу по proc для получения более подробной информации, но в целом вы можете прочитать / proc / [number] / stat, чтобы получить информацию о процессе. Это также используется командой 'ps'.

Все поля и их спецификаторы формата scanf задокументированы в proc manpag e.

Вот некоторая информация из man-страница скопирована (она довольно длинная):

          pid %d The process ID.

          comm %s
                 The  filename of the executable, in parentheses.  This is
                 visible whether or not the executable is swapped out.

          state %c
                 One character from the string "RSDZTW" where  R  is  runâ
                 ning,  S is sleeping in an interruptible wait, D is waitâ
                 ing in uninterruptible disk sleep,  Z  is  zombie,  T  is
                 traced or stopped (on a signal), and W is paging.

          ppid %d
                 The PID of the parent.

          pgrp %d
                 The process group ID of the process.

          session %d
                 The session ID of the process.

          tty_nr %d
                 The tty the process uses.

          tpgid %d
                 The  process group ID of the process which currently owns
                 the tty that the process is connected to.
4
ответ дан 24 November 2019 в 06:17
поделиться

Обратите внимание на команду "pidstat", она звучит именно так, как вам нужно.

2
ответ дан 24 November 2019 в 06:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: