Windowsta sistem fonksiyonlari ile cpu kullanımını öğrenme

windows
cpuload
c++

#1

Bunu da not olsun lazim olan kullansin diye ekleyelim.

// how to get cpu usage on windows with system calls
//iyasar

#include "stdafx.h"
#include <string>
#include <iostream>
#include <thread>
#include <chrono>


#include <Windows.h>
#include <iphlpapi.h>
#include <TCHAR.h>
#include <pdh.h>
#include <tlhelp32.h>


using namespace std;

float calculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
	static unsigned long long _previousTotalTicks = 0;
	static unsigned long long _previousIdleTicks = 0;

	unsigned long long totalTicksSinceLastTime = totalTicks - _previousTotalTicks;
	unsigned long long idleTicksSinceLastTime = idleTicks - _previousIdleTicks;

	float ret = 1.0f - ((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime) / totalTicksSinceLastTime : 0);

	_previousTotalTicks = totalTicks;
	_previousIdleTicks = idleTicks;
	return ret;
}

unsigned long long fileTimeToInt64(const FILETIME & ft)
{
	return (((unsigned long long)(ft.dwHighDateTime)) << 32) | ((unsigned long long)ft.dwLowDateTime);
}

int getCpuUsage()
{

	FILETIME idleTime, kernelTime, userTime;

	return (GetSystemTimes(&idleTime, &kernelTime, &userTime) ? calculateCPULoad(fileTimeToInt64(idleTime),
		fileTimeToInt64(kernelTime) + fileTimeToInt64(userTime)) : -1.0f) * 100;
}


int main()
{
	while (true) {
		this_thread::sleep_for(chrono::seconds(1));
		cout << "%" << getCpuUsage() << endl;
	}

    return 0;
}

Ornek ekran ciktisi: