Message

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include "mainwindow.

h"
#include "ui_mainwindow.h"
#include <QSharedPointer>
#include <QLabel>
#include <QTimer>
#include <fstream>
#include <vector>
#include <string>
#include <QStringList>
#include <QProcess>
#include <QTime>
#include <sstream>
#include <windows.h>
#include <psapi.h>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

QTimer *timer = new QTimer;


cpuPersent = new QLabel(this);
cpuPersent->setGeometry(QRect(QPoint(40, 270),QSize(50, 20)));
cpuPersent->setText("CPU");
cpuPersent->setStyleSheet("QLabel { color : blue; }");
cpu = new QLabel(this);
cpu->setGeometry(QRect(QPoint(80, 270),QSize(50, 20)));
memoryPersent = new QLabel(this);
memoryPersent->setGeometry(QRect(QPoint(130, 270),QSize(60, 20)));
memoryPersent->setText("Memory");
memoryPersent->setStyleSheet("QLabel { color : red; }");
memory = new QLabel(this);
memory->setGeometry(QRect(QPoint(200, 270),QSize(50, 20)));
memoryTotal = new QLabel(this);
memoryTotal->setGeometry(QRect(QPoint(140, 295),QSize(160, 20)));
memoryTotalTitle = new QLabel(this);
memoryTotalTitle->setGeometry(QRect(QPoint(40, 295),QSize(90, 20)));
memoryTotalTitle->setText("Total Memory:");
memoryUsed = new QLabel(this);
memoryUsed->setGeometry(QRect(QPoint(140, 320),QSize(160, 20)));
memoryUsedTitle = new QLabel(this);
memoryUsedTitle->setGeometry(QRect(QPoint(40, 320),QSize(90, 20)));
memoryUsedTitle->setText("Memory used:");

customPlot = new QCustomPlot(); // Ініціалізація графічного полотна


ui->gridLayout->addWidget(customPlot, 0, 0, 1, 1); //додавання графічного
полотна на gridLayout
customPlot->addGraph(); //перший графік – завантаження процесора
customPlot->graph(0)->setPen(QPen(QColor(40, 110, 255))); // встановлення
кольору для першого графіка – синій
customPlot->addGraph(); //другий графік – завантаження пам’яті
customPlot->graph(1)->setPen(QPen(QColor(255, 110, 40))); // встановлення
кольору для другого графіка – червоний
//налаштування вісей
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%m:%s"); //формат часу
customPlot->xAxis->setTicker(timeTicker); //додавання по вісі абсцис часу
customPlot->axisRect()->setupFullAxesBox();
customPlot->yAxis->setRange(0, 100); //встановлення меж для вісі ординат
// задання можливості вибору графіку мишею та масштабування (шляхом прокрутки
колеса миші)
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom |
QCP::iSelectPlottables);
// з’єднання сигналу таймера timeout() зі слотом
connect(timer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
timer->start(0); //Запуск таймера з встановленим інтервалом – 0
}

QString MainWindow::mesure(int n)
{
QString e;
int gb = (n / 1024) / 1024;
int mb = (n - gb * 1024 * 1024) / 1024;
int kb = (n - (gb * 1024 * 1024 + mb * 1024));
if (gb > 0)
e = QString::number(gb) + QString(" Gb ");
else
e = QString("");
if (mb > 0)
e += QString::number(mb) + QString(" Mb ");
if (kb > 0)
e += QString::number(kb) + QString(" Kb ");
return e;
}

int MainWindow::getMemoryLoad(QString& MemoryPresent, QString& MemoryUsed)


{
MEMORYSTATUSEX memoryStatus;
memoryStatus.dwLength = sizeof(memoryStatus);
GlobalMemoryStatusEx(&memoryStatus);

unsigned long long totalMemory = memoryStatus.ullTotalPhys;


unsigned long long freeMemory = memoryStatus.ullAvailPhys;
unsigned long long usedMemory = totalMemory - freeMemory;

int memoryLoad = static_cast<int>((usedMemory * 100.0) / totalMemory);

// Format memory sizes


MemoryPresent = mesure(totalMemory);
MemoryUsed = mesure(usedMemory);

return memoryLoad;
}

void MainWindow::realtimeDataSlot()
{
static QTime time(QTime::currentTime());
// визначенню двох нових точок для вибірки даних
double key = QTime::currentTime().msecsSinceStartOfDay() / 1000.0;
// час, що пройшов з моменту запуску – перша точка
static double lastPointKey = 0; //друга точка
if (key - lastPointKey > 0.002) // оновлення кожні 2 мс
{
// виведення даних
int cpu_persent = getCpuLoad(1);
customPlot->graph(0)->addData(key, cpu_persent);
cpu->setText(QString::number(cpu_persent) + '%');
lastPointKey = key;
QString total, used;
int memory_persent = getMemoryLoad(total, used);
customPlot->graph(1)->addData(key, memory_persent);
memory->setText(QString::number(memory_persent) + '%');
memoryTotal->setText(total);
memoryUsed->setText(used);
k++;
}
if (k > 4) //прокрутка графіку буде відбуватись після 4 секунд.
customPlot->xAxis->setRange(key, 4, Qt::AlignRight); //зсув (прокрутка)
графіку з константою 4
customPlot->replot();
}

int MainWindow::getCpuLoad(double dt)


{
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
static HANDLE self;
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;

GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;

GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));

self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;

return static_cast<int>(percent * 100);


}

MainWindow::~MainWindow()
{
delete ui;
}

You might also like