C: get CPU load (функция выдаёт значения более 100%)

Модератор: Модераторы разделов

IMB
Сообщения: 2567
ОС: Debian

C: get CPU load

Сообщение IMB »

Доброго дня!
Есть следующая функция от производителя:

Код: Выделить всё

******************************************************************************
 * Cpu_getLoad
 ******************************************************************************/
Int Cpu_getLoad(Cpu_Handle hCpu, Int *cpuLoad)
{
    int                  cpuLoadFound = FALSE;
    unsigned long        user, nice, sys, idle, total, proc;
    unsigned long        uTime, sTime, cuTime, csTime;
    unsigned long        deltaTotal, deltaIdle, deltaProc;
    char                 textBuf[4];
    FILE                *fptr;

    /* Read the overall system information */
    fptr = fopen("/proc/stat", "r");

    if (fptr == NULL) {
        Dmai_err0("/proc/stat not found. Is the /proc filesystem mounted?\n");
        return Dmai_EIO;
    }

    /* Scan the file line by line */
    while (fscanf(fptr, "%4s %lu %lu %lu %lu %*[^\n]", textBuf,
                  &user, &nice, &sys, &idle) != EOF) {
        if (strcmp(textBuf, "cpu") == 0) {
            cpuLoadFound = TRUE;
            break;
        }
    }

    if (fclose(fptr) != 0) {
        return Dmai_EIO;
    }

    if (!cpuLoadFound) {
        return Dmai_EFAIL;
    }

    /* Read the current process information */
    fptr = fopen("/proc/self/stat", "r");

    if (fptr == NULL) {
        Dmai_err0("/proc/self/stat not found. Is /proc filesystem mounted?\n");
        return Dmai_EIO;
    }

    if (fscanf(fptr, "%*d %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %lu "
                     "%lu %lu %lu", &uTime, &sTime, &cuTime, &csTime) != 4) {
        Dmai_err0("Failed to get process load information.\n");
        fclose(fptr);
        return Dmai_EIO;
    }

    if (fclose(fptr) != 0) {
        return Dmai_EFAIL;
    }

    total = user + nice + sys + idle;
    proc = uTime + sTime + cuTime + csTime;

    /* Check if this is the first time, if so init the prev values */
    if (hCpu->prevIdle == 0 && hCpu->prevTotal == 0 && hCpu->prevProc == 0) {
        hCpu->prevIdle = idle;
        hCpu->prevTotal = total;
        hCpu->prevProc = proc;
        return Dmai_EOK;
    }

    deltaIdle = idle - hCpu->prevIdle;
    deltaTotal = total - hCpu->prevTotal;
    deltaProc = proc - hCpu->prevProc;

    hCpu->prevIdle = idle;
    hCpu->prevTotal = total;
    hCpu->prevProc = proc;

//    *cpuLoad = 100 - deltaIdle * 100 / deltaTotal;
//    *procLoad = deltaProc * 100 / deltaTotal;
    *cpuLoad = deltaProc * 100 / deltaTotal;

    return Dmai_EOK;
}

Проблема в том, что она выдаёт неверные значения, очень часто я получаю значения больше 100%.
Используемый процессор:

Код: Выделить всё

Processor       : ARM926EJ-S rev 5 (v5l)
BogoMIPS        : 33.48
Features        : swp half thumb fastmult edsp java
CPU implementer : 0x41
CPU architecture: 5TEJ
CPU variant     : 0x0
CPU part        : 0x926
CPU revision    : 5
Cache type      : write-back
Cache clean     : cp15 c7 ops
Cache lockdown  : format C
Cache format    : Harvard
I size          : 16384
I assoc         : 4
I line length   : 32
I sets          : 128
D size          : 8192
D assoc         : 4
D line length   : 32
D sets          : 64

Hardware        : DaVinci DM355 EVM
Revision        : 3500000
Serial          : 0000000000000000

Я прочитал доступную информацию по /proc, но не нашёл расшифровки строк в /proc/self/stat.
Можете подсказать?
Спасибо.
Спасибо сказали:
Аватара пользователя
anonymous.ru
Сообщения: 614

Re: C: get CPU load

Сообщение anonymous.ru »

IMB писал(а):
08.11.2010 17:45
Проблема в том, что она выдаёт неверные значения, очень часто я получаю значения больше 100%.

забавно :)
А сколько ядер в системе?
UPD не заметил инфу по процессору :(

IMB писал(а):
08.11.2010 17:45
Я прочитал доступную информацию по /proc, но не нашёл расшифровки строк в /proc/self/stat.

man proc

Код:

/proc/self This directory refers to the process accessing the /proc filesystem, and is identical to the /proc directory named by the process ID of the same process. /proc/[number]/stat Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c. The fields, in order, with their proper scanf(3) format specifiers, are: 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 running, S is sleeping in an interruptible wait, D is waiting 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. flags %lu The kernel flags word of the process. For bit meanings, see the PF_* defines in <linux/sched.h>. Details depend on the kernel version. minflt %lu The number of minor faults the process has made which have not required loading a memory page from disk. cminflt %lu The number of minor faults that the process's waited-for children have made. majflt %lu The number of major faults the process has made which have required loading a memory page from disk. cmajflt %lu The number of major faults that the process's waited-for children have made. utime %lu The number of jiffies that this process has been scheduled in user mode. stime %lu The number of jiffies that this process has been scheduled in kernel mode. cutime %ld The number of jiffies that this process's waited-for children have been scheduled in user mode. (See also times(2).) cstime %ld The number of jiffies that this process's waited-for children have been scheduled in kernel mode. priority %ld The standard nice value, plus fifteen. The value is never negative in the kernel. nice %ld The nice value ranges from 19 (nicest) to -19 (not nice to others). 0 %ld This value is hard coded to 0 as a placeholder for a removed field. itrealvalue %ld The time in jiffies before the next SIGALRM is sent to the process due to an interval timer. starttime %lu The time in jiffies the process started after system boot. vsize %lu Virtual memory size in bytes. rss %ld Resident Set Size: number of pages the process has in real memory, minus 3 for administrative purposes. This is just the pages which count towards text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out. rlim %lu Current limit in bytes on the rss of the process (usually 4294967295 on i386). startcode %lu The address above which program text can run. endcode %lu The address below which program text can run. startstack %lu The address of the start of the stack. kstkesp %lu The current value of esp (stack pointer), as found in the kernel stack page for the process. kstkeip %lu The current EIP (instruction pointer). signal %lu The bitmap of pending signals. blocked %lu The bitmap of blocked signals. sigignore %lu The bitmap of ignored signals. sigcatch %lu The bitmap of caught signals. wchan %lu This is the "channel" in which the process is waiting. It is the address of a system call, and can be looked up in a namelist if you need a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.) nswap %lu Number of pages swapped (not maintained). cnswap %lu Cumulative nswap for child processes (not maintained). exit_signal %d Signal to be sent to parent when we die. processor %d CPU number last executed on. rt_priority %lu (since kernel 2.5.19) Real-time scheduling priority (see sched_setscheduler(2)). policy %lu (since kernel 2.5.19) Scheduling policy (see sched_setscheduler(2)).
:drinks:
Спасибо сказали:
IMB
Сообщения: 2567
ОС: Debian

Re: C: get CPU load

Сообщение IMB »

Нет, мне надо получить общую загрузку. Хотя, скорее всего, /proc/self/stat имеет тот же формат.
Так какого же....?
Спасибо сказали: