C语言实现监控windows的cpu的top10进程
时间: 2024-02-16 12:00:30 浏览: 267
windows版本的进程监控,C#基于多线程Quartz实现,每10秒监测一次.zip
要实现C语言监控Windows的CPU的Top 10进程,可以考虑以下步骤:
1. 使用Windows API的函数获取当前进程列表,包括每个进程的PID和CPU占用率等信息。
2. 将获取到的每个进程的CPU占用率进行排序,找出占用率最高的Top 10进程。
3. 将Top 10进程的PID和CPU占用率等信息记录下来,可以输出到控制台、日志文件或者发送到其他应用程序进行处理。
下面是一个简单的C语言代码示例,可以实现监控Windows的CPU的Top 10进程:
```
#include <windows.h>
#include <stdio.h>
#define MAX_PROCESSES 1024
typedef struct {
DWORD pid;
float cpu_usage;
} PROCESS_INFO;
int compare_process_info(const void *a, const void *b) {
const PROCESS_INFO *pa = (const PROCESS_INFO *)a;
const PROCESS_INFO *pb = (const PROCESS_INFO *)b;
if (pa->cpu_usage > pb->cpu_usage) {
return -1;
} else if (pa->cpu_usage < pb->cpu_usage) {
return 1;
} else {
return 0;
}
}
int main() {
PROCESS_INFO processes[MAX_PROCESSES];
DWORD num_processes = 0;
float cpu_total = 0.0f;
while (1) {
// 获取进程列表
DWORD cbNeeded;
DWORD processIds[MAX_PROCESSES];
if (!EnumProcesses(processIds, sizeof(processIds), &cbNeeded)) {
printf("Error: EnumProcesses failed!\n");
break;
}
num_processes = cbNeeded / sizeof(DWORD);
// 计算每个进程的CPU占用率
cpu_total = 0.0f;
for (DWORD i = 0; i < num_processes; ++i) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIds[i]);
if (hProcess) {
FILETIME dummy, creationTime, exitTime, kernelTime, userTime;
if (GetProcessTimes(hProcess, &dummy, &dummy, &kernelTime, &userTime) &&
GetSystemTimeAsFileTime(&dummy) &&
GetProcessTimes(hProcess, &creationTime, &exitTime, &dummy, &dummy)) {
ULARGE_INTEGER kernelTimeLarge, userTimeLarge;
kernelTimeLarge.LowPart = kernelTime.dwLowDateTime;
kernelTimeLarge.HighPart = kernelTime.dwHighDateTime;
userTimeLarge.LowPart = userTime.dwLowDateTime;
userTimeLarge.HighPart = userTime.dwHighDateTime;
float cpu_usage = (kernelTimeLarge.QuadPart + userTimeLarge.QuadPart) / (10000.0f * GetTickCount());
processes[i].pid = processIds[i];
processes[i].cpu_usage = cpu_usage;
cpu_total += cpu_usage;
}
CloseHandle(hProcess);
}
}
// 排序并输出Top 10进程
qsort(processes, num_processes, sizeof(PROCESS_INFO), compare_process_info);
printf("Top 10 processes:\n");
for (DWORD i = 0; i < 10 && i < num_processes; ++i) {
if (processes[i].cpu_usage > 0.0f) {
printf("PID: %d, CPU usage: %.2f%%\n", processes[i].pid, processes[i].cpu_usage * 100);
}
}
printf("Total CPU usage: %.2f%%\n", cpu_total * 100);
Sleep(1000);
}
return 0;
}
```
该代码使用了`EnumProcesses`和`GetProcessTimes`等Windows API函数,可以获取进程列表和每个进程的CPU占用率等信息,然后使用`qsort`函数对进程列表进行排序,输出Top 10进程和总CPU占用率。该代码可以作为一个Windows服务运行,不断监控系统中的进程情况,并输出Top 10进程的信息。
阅读全文