How to determine CPU and memory consumption from inside a process?

后端 未结 9 1578
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 11:28

I once had the task of determining the following performance parameters from inside a running application:

  • Total virtual memory available
  • Virtual memo
9条回答
  •  伪装坚强ぢ
    2020-11-21 12:12

    I used this following code in my C++ project and it worked fine:

    static HANDLE self;
    static int numProcessors;
    SYSTEM_INFO sysInfo;
    
    double percent;
    
    numProcessors = sysInfo.dwNumberOfProcessors;
    
    //Getting system times information
    FILETIME SysidleTime;
    FILETIME SyskernelTime; 
    FILETIME SysuserTime; 
    ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
    GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
    memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
    memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
    __int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  
    
    //Getting process times information
    FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
    ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
    GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
    memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
    memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
    __int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
    //QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)
    
    percent = 100*(numerator/denomenator);
    

提交回复
热议问题