【发布时间】:2017-01-28 23:34:14
【问题描述】:
我在 google 上找到了这段代码,它计算了 win10 上当前进程的使用百分比,但我正在寻找的是每个进程的 CPU 使用百分比的列表。 我使用 GetCurrentProcess() 来获取当前进程的句柄。有没有办法检索每个进程的句柄?我正在编写一个代码,列出正在运行的进程并计算每个人的使用内存。然后我需要计算每个人的 cpu 使用率,但我在 google 上没有找到任何东西。
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
static HANDLE self;
void init(){
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
}
double getCurrentValue(){
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
long double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(GetCurrentProcess(), &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 percent * 100;
}
I'm able to have the list of all running processes but i'm looking for to
calculate cpu usage for every process.
Suggestions?
【问题讨论】:
-
获取您可以使用的所有进程的列表或
CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );或ZwQuerySystemInformation(SystemProcessInformation, buf, cb, &rcb),然后使用PROCESS_QUERY_LIMITED_INFORMATION打开进程并且您需要在令牌中启用调试权限 -
我做到了,但它不起作用。我不知道如何添加整个代码,但我使用了 Create Toolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);使用 hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe32.th32ProcessID) 获取所有进程列表和 openprocess;之后我调用了 Init() 和 getCurrentValue() 但它不起作用
-
什么混凝土不起作用?出现什么错误?
-
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)) { printError(TEXT("Process32First"));关闭句柄(hProcessSnap); } 做 {_tprintf(TEXT("\nPROCESS NAME: %s \t"), pe32.szExeFile); hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe32.th32ProcessID);
-
和?什么问题?