通过PID获取进程的CPU使用率(顶级源代码) [英] get CPU usage for process by PID (top source code)

查看:120
本文介绍了通过PID获取进程的CPU使用率(顶级源代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只知道 PID,如何获取进程的 CPU 使用率?MAXOS X

How can I get CPU usage for process if i know only PID? MAXOS X

我查看了 MACOSX 的顶级实用程序源代码和我在libtop.c中发现了几个重要的函数

I looked through top utility source codes for MACOSX and I have found several important functions in libtop.c

/* Iterate through all processes and update their statistics. */
libtop_p_proc_table_read(boolean_t reg)

libtop_p_task_update() 

/* Get CPU usage statistics.    */
libtop_pinfo_update_cpu_usage() 

问题是我不明白他们是如何从如此庞大的数量中获得 %CPU 使用率的MACOS 特定的mach 内核"系统调用.有人有解决方案吗?

The problem is that I don't understand how they get %CPU usage from this huge amout of MACOS specific "mach kernel" system calls. Does anybody have solution for this?

我是他们获得 system_time、user_time、total_time 的来源.
我 total_time 是从进程开始的时间还是什么?或者可能是 total_time 等于 1 秒.

I the source they get system_time, user_time , total_time.
I total_time is time from process start or what? Or may be total_time is equal 1 sec.

例如我的结果:对于 Opera 浏览器:

For example my results: for Opera Browser:

pid:1214 user:653.517582sec system:193.597306sec total:847.114888sec

pid:1214 user:653.517582sec system:193.597306sec total:847.114888sec

来自顶级实用程序的正确信息:

Correct info from top utility:

PID 命令 %CPU 时间
1214-歌剧 8.0 14:04.52

PID COMMAND %CPU TIME
1214- Opera 8.0 14:04.52

我不明白如何将我的结果转换为 8.0%.这里的总时间是用户时间和系统时间的总和.总时间是正确的:847 秒大约是 14 分 04 秒要获得 cpu 使用百分比,我需要所有进程的空闲时间.

I dont understand how to convert my results to 8.0%. Total time here is a sum of user time and system time. Total time is correct: 847sec is approx 14min 04 sec To get cpu usage percent i need something like idle time for all process.

我已经花了一整天但没有任何预付款.

I have already spend the whole day but without any advance.

推荐答案

查看 https://chromium.googlesource.com/chromium/src/+/master/base/process/process_metrics_mac.cc 了解这是如何在 chrome 的任务管理器中实现的.

Look at GetCPUUsage() in https://chromium.googlesource.com/chromium/src/+/master/base/process/process_metrics_mac.cc for how this is implemented in chrome's task manager.

这篇关于通过PID获取进程的CPU使用率(顶级源代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆