c++/c#系统和程序资源监控-Windows

c++/c#系统和程序资源监控-Windows,c#,c++,resources,monitor,C#,C++,Resources,Monitor,我正在考虑制作一个改进版的Windows资源监视器,它不仅包括资源使用情况,还包括硬件状态,如温度和风扇转速 我昨天开始使用C++编程,我已经成功地列出并刷新了我的计算机上的每个进程的内存和CPU利用率。 然而,问题来了:速度太慢了。它使用了我i5的5%2500k@4.3当每秒轮询一次使用情况时。这是不可接受的,因为我不仅需要CPU和内存的使用,还需要每个硬盘的磁盘使用、互联网使用、GPU使用(每个进程都需要),然后我还需要监控所有的温度 这是我的密码: const double MB = 10

我正在考虑制作一个改进版的Windows资源监视器,它不仅包括资源使用情况,还包括硬件状态,如温度和风扇转速

我昨天开始使用C++编程,我已经成功地列出并刷新了我的计算机上的每个进程的内存和CPU利用率。 然而,问题来了:速度太慢了。它使用了我i5的5%2500k@4.3当每秒轮询一次使用情况时。这是不可接受的,因为我不仅需要CPU和内存的使用,还需要每个硬盘的磁盘使用、互联网使用、GPU使用(每个进程都需要),然后我还需要监控所有的温度

这是我的密码:

const double MB = 1024*1024;
const double KB = 1024;

struct WinProcess
{
    wstring Name;
    unsigned int ID;
    wstring UserName;
    double cpuUsage;
    long long int ramUsage;

    WinProcess(wstring name, unsigned int id) : Name(name), ID(id), UserName(L"Not set"), cpuUsage(0), ramUsage(0) {}
};

class ResourceMonitor
{
private:
    void** hquery;
    void** hcountercpu;
    void** hcountermem;

    int cpuCores;

    vector<WinProcess> Processes;
public:
    ResourceMonitor();
    ~ResourceMonitor();

    void StartResourceMonitor();
    void MeasureResourceUsage();
    void PrintUsage();
};

ResourceMonitor::ResourceMonitor() : 
    Processes(GetProcessList())    // Function GetProcessList() returns vector with all processes, their IDs and username, from which it was launched
{
    hquery = new void*[Processes.size()];
    hcountercpu = new void*[Processes.size()];
    hcountermem = new void*[Processes.size()];

    for (unsigned int i = 2; i < Processes.size(); i++)
    {
        Processes[i].Name = Processes[i].Name.substr(0, Processes[i].Name.size() - 4);
    }

    for (unsigned int i = 2; i < Processes.size(); i++)
    {
        wstring CounterPathCPU = L"\\Process(" + Processes[i].Name + L")\\% Processor Time";
        wstring CounterPathMEM = L"\\Process(" + Processes[i].Name + L")\\Private Bytes";

        if ((PdhOpenQuery(NULL, 0, &hquery[i])) != ERROR_SUCCESS
            || PdhAddCounter(hquery[i], CounterPathCPU.c_str(), 0, &hcountercpu[i]) != ERROR_SUCCESS
            || PdhAddCounter(hquery[i], CounterPathMEM.c_str(), 0, &hcountermem[i]) != ERROR_SUCCESS
            || PdhCollectQueryData(hquery[i]) != ERROR_SUCCESS)
        {
            continue;
        }
    }

    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    cpuCores = sysinfo.dwNumberOfProcessors;

    wcout.setf(ios::fixed);
}

ResourceMonitor::~ResourceMonitor()
{    
    for (unsigned int i = 2; i < Processes.size(); i++)
    {
        PdhCloseQuery(hquery[i]);
        PdhRemoveCounter(hcountercpu[i]);
        PdhRemoveCounter(hcountermem[i]);
    }

    delete[] hquery;
    delete[] hcountercpu;
}

void ResourceMonitor::StartResourceMonitor()
{
    system("mode CON: COLS=150");

    while (1)
    {
        MeasureResourceUsage();
        PrintUsage();
        Sleep(1000);
    }
}

void ResourceMonitor::MeasureResourceUsage()
{
    PDH_FMT_COUNTERVALUE countervalcpu;
    PDH_FMT_COUNTERVALUE countervalmem;

    for (unsigned int i = 2; i < Processes.size(); i++)
    {
        if ((PdhCollectQueryData(hquery[i])) != ERROR_SUCCESS)
        {   
            printError(L"Error on collecting query data: ");
            continue;
        }        
        if ((PdhGetFormattedCounterValue(hcountercpu[i], PDH_FMT_LONG | PDH_FMT_NOCAP100, 0, &countervalcpu)) != ERROR_SUCCESS)
        {
            printError(L"Error on CPU usage retrieval: ");
            continue;
        }
        if ((PdhGetFormattedCounterValue(hcountermem[i], PDH_FMT_LONG, 0, &countervalmem)) != ERROR_SUCCESS)
        {
            printError(L"Error on Memory usage retrieval: ");
            continue;
        }

        Processes[i].cpuUsage = countervalcpu.longValue / (double)cpuCores;
        Processes[i].ramUsage = countervalmem.longValue;
    }
}

void ResourceMonitor::PrintUsage()
{
    system("cls");
    long long int RAMSUM = 0;
    for (unsigned int i = 2; i < Processes.size(); i++)
    {
        wcout << left << setw(40) << Processes[i].Name + L".exe: ";
        wcout << setw(6) << left << L" | ID " << setw(4) << right << Processes[i].ID;
        wcout << setw(8) << left << L" | User " << setw(15) << Processes[i].UserName;
        wcout << setw(8) << left << L" | CPU usage " << setw(10) << right << setprecision(2) << Processes[i].cpuUsage << setw(1) << L"%";
        wcout << setw(8) << left << L" | RAM usage " << setw(15) << right << setprecision(3) << Processes[i].ramUsage / MB << setw(3) << left << L" MB" << endl;

        RAMSUM += Processes[i].ramUsage;
    }
    wcout << L"Total RAM usage: " << setw(7) << right << RAMSUM / MB
        << setw(3) << left << L" MB" << endl;
}
常量双MB=1024*1024; 常数双KB=1024; 结构WinProcess { 字符串名称; 无符号整数ID; wstring用户名; 双cpuUsage; 长时间使用; WinProcess(wstring name,unsigned int-id):名称(name),id(id),用户名(L“未设置”),cpuUsage(0),ramUsage(0){ }; 类资源监视器 { 私人: 作废**查询; 无效**hcountercpu; 无效**hCounterem; int cpuCores; 向量过程; 公众: ResourceMonitor(); ~ResourceMonitor(); void StartResourceMonitor(); void measuresourceusage(); 无效打印用法(); }; ResourceMonitor::ResourceMonitor(): 进程(GetProcessList())//函数GetProcessList()返回所有进程及其ID和用户名的向量,从中启动该进程 { hquery=newvoid*[processs.size()]; hcountercpu=newvoid*[processs.size()]; hcountermem=newvoid*[processs.size()]; for(无符号整数i=2;iwcout上次使用cpu和mem统计数据时,我使用的是Delphi,但这些调用几乎都直接进入了windows API。我在这个答案的末尾包含了Delphi/pascal源代码,因此您可以看到我使用的实际代码。这包括cpu和内存使用情况,但我没有回答您最后一个关于网络流量的问题,disk us年龄和GPU使用情况

这些链接涵盖了我使用的技术,但对于c/c++,对于c#,这些都很好地封装在类中,并且非常容易访问

内存使用情况:

CPU时间:

//此成员变量在函数中引用
mLastMemInfo:tprocessremorycounters;
过程TProcess.UpdateStats(句柄:基数);
变量
创建、退出、内核、用户:FILETIME;
系统时间:t系统时间;
iKernel:Int64;
iUser:Int64;
总时间:Int64;
滴答声:红衣主教;
特德尔塔:红衣主教;
开始
如果(句柄无效\u句柄),则开始
tickCount:=GetTickCount;
tDelta:=滴答声计数-mLastStatsTick;
//仅在自上次检查后500毫秒或更长时间内更新统计信息
//或者如果我们还没有检查过的话
如果(tDelta>=500),则开始
//获取cpu统计数据
如果GetProcessTimes(句柄、创建、退出、内核、用户),则开始
如果(mCreationTime=0),则开始
如果是(FileTimeToSystemTime(创建,系统时间)),则开始
mCreationTime:=SystemTimeToDateTime(系统时间);
结束;
结束;
iKernel:=kernel.dwHighDateTime;
iKernel:=(iKernel shl 32)或kernel.dwLowDateTime;
iUser:=user.dwHighDateTime;
iUser:=(iUser shl 32)或user.dwLowDateTime;
iKernel:=iKernel div 10;//将100毫微秒转换为微秒
iUser:=iUser第10部分;
// this member var is referenced within the function
mLastMemInfo: TProcessMemoryCounters;

procedure TProcess.UpdateStats(handle: Cardinal);
var
  creation, exit, kernel, user: FILETIME;
  sysTime: TSystemTime;
  iKernel: Int64;
  iUser: Int64;
  totalTime: Int64;
  tickCount: Cardinal;
  tDelta: Cardinal;
begin
  if (handle <> INVALID_HANDLE) then begin
    tickCount := GetTickCount;
    tDelta := tickCount - mLastStatsTick;
    // only update stats if its been 500 ms or more since last check
    // or if we haven't checked at all yet
    if (tDelta >= 500) then begin
      // get cpu stats
      if GetProcessTimes(handle, creation, exit, kernel, user) then begin
        if (mCreationTime = 0) then begin
          if (FileTimeToSystemTime(creation, sysTime)) then begin
            mCreationTime := SystemTimeToDateTime(sysTime);
          end;
        end;
        iKernel := kernel.dwHighDateTime;
        iKernel := (iKernel shl 32) or kernel.dwLowDateTime;
        iUser := user.dwHighDateTime;
        iUser := (iUser shl 32) or user.dwLowDateTime;
        iKernel := iKernel div 10; // convert 100nanos to microseconds
        iUser := iUser div 10; // convert 100nanos to microseconds
        mLastKernelDelta := iKernel - mLastKernelTime;
        mLastUserDelta := iUser - mLastUserTime;
        totalTime := mLastKernelDelta + mLastUserDelta;
        if (totalTime <= 0) and (mLastStatsTick = 0) then begin
          mLastCpuUsage := 0;
        end else begin
          mLastCpuUsage := (totalTime / NumberOfProcessors) / (tDelta * 1000);
          if (mLastCpuUsage > 1.0) then mLastCpuUsage := 1.0;
        end;
        mLastKernelTime := iKernel;
        mLastUserTime := iUser;
      end else begin
        mLastCpuUsage := 0;
      end;
      // get memory stats
      mLastMemInfo.cb := SizeOf(mLastMemInfo);
      if not GetProcessMemoryInfo(handle, @mLastMemInfo,
                    SizeOf(mLastMemInfo)) then begin
        mLastMemInfo.cb := 0; // flag data as no good
      end;
      // set the time we got the stats
      mLastStatsTick := tickCount;
    end;
  end;
end;