目前,我需要计算macOS平台上某个进程的cpu使用率(目标进程与当前进程没有直接关系)。我使用符合性 API。计算方法是每隔一段时间调用一次,然后计算ri_user_time和ri_system_time的时间差。从而计算cpu使用率的百分比。
我在一个非M1芯片的macOS系统上使用了它,结果与预期一致(基本上和我在活动监视器上看到的一样),但是最近我发现在macOS系统上使用M1芯片获得的值很小。例如,我的进程之一(从活动监视器)消耗了的30+%,它的小于1%。
我提供了一个演示代码,您可以直接创建一个新项目来运行:
//
// main.cpp
// SimpleMonitor
//
// Created by m1 on 2021/2/23.
//
#include <stdio.h>
#include <stdlib.h>
#include <libproc.h>
#include <stdint.h>
#include <iostream>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "run simple monitor!\n";
// TODO: change process id:
int64_t pid = 12483;
struct rusage_info_v4 ru;
struct rusage_info_v4 ru2;
int64_t success = (int64_t)proc_pid_rusage((pid_t)pid, RUSAGE_INFO_V4, (rusage_info_t *)&ru);
if (success != 0) {
std::cout << "get cpu time fail \n";
return 0;
}
std::cout<<"getProcessPerformance, pid=" + std::to_string(pid) + " ru.ri_user_time=" + std::to_string(ru.ri_user_time) + " ru.ri_system_time=" + std::to_string(ru.ri_system_time)<<std::endl;
std::this_thread::sleep_for (std::chrono::seconds(10));
int64_t success2 = (int64_t)proc_pid_rusage((pid_t)pid, RUSAGE_INFO_V4, (rusage_info_t *)&ru2);
if (success2 != 0) {
std::cout << "get cpu time fail \n";
return 0;
}
std::cout<<"getProcessPerformance, pid=" + std::to_string(pid) + " ru2.ri_user_time=" + std::to_string(ru2.ri_user_time) + " ru2.ri_system_time=" + std::to_string(ru2.ri_system_time)<<std::endl;
int64_t cpu_time = ru2.ri_user_time - ru.ri_user_time + ru2.ri_system_time - ru.ri_system_time;
// percentage:
double cpu_usage = (double)cpu_time / 10 / 1000000000 * 100 ;
std::cout<<pid<<" cpu usage: "<<cpu_usage<<std::endl;
}在这里,我想知道我的计算方法是否有问题,如果没有问题,我如何处理M1芯片macOS系统上的不准确结果?
发布于 2022-07-08 18:12:15
您必须将cpu使用量乘以某个常量。下面是一些来自diff的代码片段。
+#include
~
https://stackoverflow.com/questions/66328149
复制相似问题