gpt4 book ai didi

c++ - 您如何获得进程运行了多长时间?

转载 作者:IT王子 更新时间:2023-10-29 01:10:36 26 4
gpt4 key购买 nike

有没有办法从 /proc 目录中获取这些信息?我希望能够以秒为单位了解每个进程运行了多长时间。

编辑:我需要从 C++ 执行此操作。抱歉造成混淆。

最佳答案

好吧,在阅读了 top 命令的源代码之后,我想出了一个获取进程开始时间的非 hacky 方法。他们使用的公式是:

Process_Time = (current_time - boot_time) - (process_start_time)/HZ.

(你必须除以 HZ,因为 process_start_time 是 jiffies)

获取这些值:

  • current_time - 您可以从 C 命令 gettimeofday() 中获取它。
  • boot_time - 此值位于 /proc/uptime 中。该文件包含两个数字:系统的正常运行时间(秒)和空闲进程花费的时间(秒)。拿第一个。
  • process_start_time - 此值位于 /proc/[PID]/stat 中。系统启动和进程启动之间的时间差(以 jiffies 为单位)。 (如果按空格拆分,则为文件中的第 22 个值)。

代码(抱歉,我有时会混用 c 和 c++):

  int fd;
char buff[128];
char *p;
unsigned long uptime;
struct timeval tv;
static time_t boottime;


if ((fd = open("/proc/uptime", 0)) != -1)
{
if (read(fd, buff, sizeof(buff)) > 0)
{
uptime = strtoul(buff, &p, 10);
gettimeofday(&tv, 0);
boottime = tv.tv_sec - uptime;

}
close(fd);
}


ifstream procFile;
procFile.open("/proc/[INSERT PID HERE]/stat");

char str[255];
procFile.getline(str, 255); // delim defaults to '\n'


vector<string> tmp;
istringstream iss(str);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string> >(tmp));

process_time = (now - boottime) - (atof(tmp.at(21).c_str()))/HZ;

编码愉快!

关于c++ - 您如何获得进程运行了多长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6514378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com