进程使用的 CPU 时间

发布于 2024-09-11 09:58:30 字数 3896 浏览 3 评论 0原文

我已成功实现此列表上的代码以获得所有正在运行的进程及其 ID 的列表。我现在需要的是提取每个进程使用CPU的时间。

我尝试引用代码中的键,但是当我尝试打印“CPU 时间滴答”时,所有进程的值都为零。另外,即使我确实获得了一个值,我也不确定“CPU 时间滴答”是否正是我正在寻找的。

struct  vmspace *p_vmspace; /* Address space. */
struct  sigacts *p_sigacts; /* Signal actions, state (PROC ONLY). */
int p_flag;         /* P_* flags. */
char    p_stat;         /* S* process status. */
pid_t   p_pid;          /* Process identifier. */
pid_t   p_oppid;     /* Save parent pid during ptrace. XXX */
int p_dupfd;     /* Sideways return value from fdopen. XXX */
/* Mach related  */
caddr_t user_stack; /* where user stack was allocated */
void    *exit_thread;   /* XXX Which thread is exiting? */
int     p_debugger;     /* allow to debug */
boolean_t   sigwait;    /* indication to suspend */
/* scheduling */
u_int   p_estcpu;    /* Time averaged value of p_cpticks. */
int p_cpticks;   /* Ticks of cpu time. */
fixpt_t p_pctcpu;    /* %cpu for this process during p_swtime */
void    *p_wchan;    /* Sleep address. */
char    *p_wmesg;    /* Reason for sleep. */
u_int   p_swtime;    /* Time swapped in or out. */
u_int   p_slptime;   /* Time since last blocked. */
struct  itimerval p_realtimer;  /* Alarm timer. */
struct  timeval p_rtime;    /* Real time. */
u_quad_t p_uticks;      /* Statclock hits in user mode. */
u_quad_t p_sticks;      /* Statclock hits in system mode. */
u_quad_t p_iticks;      /* Statclock hits processing intr. */
int p_traceflag;        /* Kernel trace points. */
struct  vnode *p_tracep;    /* Trace to vnode. */
int p_siglist;      /* DEPRECATED */
struct  vnode *p_textvp;    /* Vnode of executable. */
int p_holdcnt;      /* If non-zero, don't swap. */
sigset_t p_sigmask; /* DEPRECATED. */
sigset_t p_sigignore;   /* Signals being ignored. */
sigset_t p_sigcatch;    /* Signals being caught by user. */
u_char  p_priority; /* Process priority. */
u_char  p_usrpri;   /* User-priority based on p_cpu and p_nice. */
char    p_nice;     /* Process "nice" value. */
char    p_comm[MAXCOMLEN+1];
struct  pgrp *p_pgrp;   /* Pointer to process group. */
struct  user *p_addr;   /* Kernel virtual addr of u-area (PROC ONLY). */
u_short p_xstat;    /* Exit status for wait; also stop signal. */
u_short p_acflag;   /* Accounting flags. */
struct  rusage *p_ru;   /* Exit information. XXX */

事实上,我也尝试过打印 p_cpticks 和其他一些值的时间平均值,但从未得到有趣的值。这是我的代码,它打印检索到的信息(我从 cocoabuilder.com 获得):

- (NSDictionary *) getProcessList {
    NSMutableDictionary *ProcList = [[NSMutableDictionary alloc] init];

    kinfo_proc *mylist;
    size_t mycount = 0;
    mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc));
    GetBSDProcessList(&mylist, &mycount);
    printf("There are %d processes.\n", (int)mycount);

NSLog(@" = = = = = = = = = = =  = = = =");
    int k;
    for(k = 0; k < mycount; k++) {
        kinfo_proc *proc = NULL;
        proc = &mylist[k];
        // NSString *processName = [NSString stringWithFormat: @"%s",proc->kp_proc.p_comm];
         //[ ProcList setObject: processName forKey: processName ];
        //  [ ProcList setObject: proc->kp_proc.p_pid forKey: processName];
          // printf("ID: %d - NAME: %s\n", proc->kp_proc.p_pid, proc->kp_proc.p_comm);
           printf("ID: %d - NAME: %s  CPU TIME: %d     \n", proc->kp_proc.p_pid, proc->kp_proc.p_comm, proc->kp_proc.p_pid );
        // Right click on p_comm and select 'jump to definition' to find other values. 
    }


    free(mylist);

    return [ProcList autorelease];
}

谢谢!

编辑:我刚刚为这个问题提供了赏金。我具体寻找的是获取每个进程在 CPU 上花费的时间量。

除此之外,如果您可以给出进程使用的 %CPU,那就太棒了。

该代码应该是最佳的,因为它将每秒调用一次,并且该方法将在所有正在运行的进程上调用。首选 Objective-C。

再次感谢!

编辑2

此外,任何关于人们为什么忽略这个问题的评论也会有所帮助:)

I've managed to implement the code on this listing to get a list of all the processes running and their IDs. What I need now is to extract how much time each process uses the CPU.

I've tried referring to the keys in the code, but when I try to print 'Ticks of CPU Time' I get a zero value for all of the processes. Plus, even if I did get a value I'm not sure if 'Ticks of CPU Time' is exactly what I'm looking for.

struct  vmspace *p_vmspace; /* Address space. */
struct  sigacts *p_sigacts; /* Signal actions, state (PROC ONLY). */
int p_flag;         /* P_* flags. */
char    p_stat;         /* S* process status. */
pid_t   p_pid;          /* Process identifier. */
pid_t   p_oppid;     /* Save parent pid during ptrace. XXX */
int p_dupfd;     /* Sideways return value from fdopen. XXX */
/* Mach related  */
caddr_t user_stack; /* where user stack was allocated */
void    *exit_thread;   /* XXX Which thread is exiting? */
int     p_debugger;     /* allow to debug */
boolean_t   sigwait;    /* indication to suspend */
/* scheduling */
u_int   p_estcpu;    /* Time averaged value of p_cpticks. */
int p_cpticks;   /* Ticks of cpu time. */
fixpt_t p_pctcpu;    /* %cpu for this process during p_swtime */
void    *p_wchan;    /* Sleep address. */
char    *p_wmesg;    /* Reason for sleep. */
u_int   p_swtime;    /* Time swapped in or out. */
u_int   p_slptime;   /* Time since last blocked. */
struct  itimerval p_realtimer;  /* Alarm timer. */
struct  timeval p_rtime;    /* Real time. */
u_quad_t p_uticks;      /* Statclock hits in user mode. */
u_quad_t p_sticks;      /* Statclock hits in system mode. */
u_quad_t p_iticks;      /* Statclock hits processing intr. */
int p_traceflag;        /* Kernel trace points. */
struct  vnode *p_tracep;    /* Trace to vnode. */
int p_siglist;      /* DEPRECATED */
struct  vnode *p_textvp;    /* Vnode of executable. */
int p_holdcnt;      /* If non-zero, don't swap. */
sigset_t p_sigmask; /* DEPRECATED. */
sigset_t p_sigignore;   /* Signals being ignored. */
sigset_t p_sigcatch;    /* Signals being caught by user. */
u_char  p_priority; /* Process priority. */
u_char  p_usrpri;   /* User-priority based on p_cpu and p_nice. */
char    p_nice;     /* Process "nice" value. */
char    p_comm[MAXCOMLEN+1];
struct  pgrp *p_pgrp;   /* Pointer to process group. */
struct  user *p_addr;   /* Kernel virtual addr of u-area (PROC ONLY). */
u_short p_xstat;    /* Exit status for wait; also stop signal. */
u_short p_acflag;   /* Accounting flags. */
struct  rusage *p_ru;   /* Exit information. XXX */

In fact I've also tried to print Time averaged value of p_cpticks and a few others and never got interesting values. Here is my code which is printing the information retrieved (I got it from cocoabuilder.com) :

- (NSDictionary *) getProcessList {
    NSMutableDictionary *ProcList = [[NSMutableDictionary alloc] init];

    kinfo_proc *mylist;
    size_t mycount = 0;
    mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc));
    GetBSDProcessList(&mylist, &mycount);
    printf("There are %d processes.\n", (int)mycount);

NSLog(@" = = = = = = = = = = =  = = = =");
    int k;
    for(k = 0; k < mycount; k++) {
        kinfo_proc *proc = NULL;
        proc = &mylist[k];
        // NSString *processName = [NSString stringWithFormat: @"%s",proc->kp_proc.p_comm];
         //[ ProcList setObject: processName forKey: processName ];
        //  [ ProcList setObject: proc->kp_proc.p_pid forKey: processName];
          // printf("ID: %d - NAME: %s\n", proc->kp_proc.p_pid, proc->kp_proc.p_comm);
           printf("ID: %d - NAME: %s  CPU TIME: %d     \n", proc->kp_proc.p_pid, proc->kp_proc.p_comm, proc->kp_proc.p_pid );
        // Right click on p_comm and select 'jump to definition' to find other values. 
    }


    free(mylist);

    return [ProcList autorelease];
}

Thanks!

EDIT: I've just offered a bounty for this question. What I'm looking for specifically is to get the amount of time each process spends in CPU.

If, in addition to this, you can give %CPU being used by a process, that would be fantastic.

The code should be optimal in that it will be called every second and the method will be called on all running processes. Objective-C preferable.

Thanks again!

EDIT 2

Also, any comments as to why people are ignoring this question would also be helpful :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妄司 2024-09-18 09:58:30

查看 libtop.c 特别是 libtop_pinfo_update_cpu_usage() 函数。请注意:

  1. 您需要对 Mach 编程基础有基本的了解才能理解此代码,因为它使用任务端口等。
  2. 如果您想简单地使用 libtop,则必须下载源代码并自行编译。
  3. 您的进程将需要权限才能访问其他进程的任务端口。

如果这一切听起来相当令人畏惧,那么……有一种使用不太深奥的 API 的方法:只需生成一个顶级进程并解析其标准输出。快速浏览一下 top(1) 手册页会发现这个小宝石:

$ top -s 1 -l 3600 -stats pid,cpu,time

也就是说,每秒采样一次,持续 3600 秒(一小时),并以日志形式仅将 pid、cpu 使用情况和时间的统计信息输出到 stdout 。

生成和管理子顶级进程,然后解析其输出都是简单的 Unix 编程练习。

Have a look at the Darwin source for libtop.c and particularly the libtop_pinfo_update_cpu_usage() function. Note that:

  1. You'll need a basic understanding of Mach programming fundamentals to make sense of this code, as it uses task ports, etc.
  2. If you want to simply use libtop, you'll have to download the source and compile it yourself.
  3. Your process will need privileges to get at the task ports for other processes.

If all this sounds rather daunting, well… There is a way that uses less esoteric APIs: Just spawn a top process and parse its standard output. A quick glimpse over the top(1) man page turned up this little gem:

$ top -s 1 -l 3600 -stats pid,cpu,time

That is, sample once per second for 3600 seconds (one hour), and output to stdout in log form only the statistics for pid, cpu usage, and time.

Spawning and managing the child top process and then parsing its output are all straightforward Unix programming exercises.

蹲在坟头点根烟 2024-09-18 09:58:30

你看过 struct rusage 了吗?您已将其列出并评论为“退出信息”,但我知道它包含进程实际使用的资源。请查看此页面。我记得我使用 getrusage() 来计算当前进程的科学计算中使用的确切 CPU 时间量,因此您只需知道如何为列表中的每个进程查询该结构即可猜测

Have you taken a look at the struct rusage? You have listed it and commented as "Exit information" but I know that it contains the resources actually used by a process. Take a look at this page. I remember I used getrusage() for calculating the exact amount of CPU time used in my scientific calculation for my current process, so you just have to know how to query that struct for each process in you list i guess

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文