44 lines
1.1 KiB
C++
Executable File
44 lines
1.1 KiB
C++
Executable File
#include "cpuworker.h"
|
|
#include <QProcess>
|
|
#include <QStringList>
|
|
#include <QRegularExpression>
|
|
#include <QTimer>
|
|
|
|
CPUWorker::CPUWorker(QObject *parent) : QObject(parent)
|
|
{
|
|
}
|
|
|
|
void CPUWorker::process()
|
|
{
|
|
QTimer *timer = new QTimer(this);
|
|
connect(timer, &QTimer::timeout, this, &CPUWorker::fetchCpuUsage);
|
|
timer->start(1000); // 每秒调用一次 fetchCpuUsage
|
|
}
|
|
|
|
void CPUWorker::fetchCpuUsage()
|
|
{
|
|
QProcess process;
|
|
QStringList arguments = QStringList() << "-P" << "ALL" << "1" << "1";
|
|
process.start("mpstat", arguments);
|
|
process.waitForFinished();
|
|
QString output = process.readAllStandardOutput();
|
|
|
|
QStringList lines = output.split("\n");
|
|
bool startParsing = false;
|
|
int coreIndex = 0;
|
|
for (const QString &line : lines) {
|
|
if (line.contains("all")) {
|
|
startParsing = true;
|
|
continue;
|
|
}
|
|
if (startParsing && !line.trimmed().isEmpty()) {
|
|
QStringList parts = line.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
|
|
if (parts.size() > 11) {
|
|
double idle = parts[11].toDouble();
|
|
double usage = 100.0 - idle;
|
|
emit dataReady(coreIndex, usage);
|
|
coreIndex++;
|
|
}
|
|
}
|
|
}
|
|
} |