微软提供了一个非常有用的API函数
GetProcessTimes
用来获取进程创建时间、销毁时间、用户态时间、内核态时间,msdn连接为:
GetProcessTimes 函数 (processthreadsapi.h)
其函数原型为:
BOOL GetProcessTimes(
[in] HANDLE hProcess,
[out] LPFILETIME lpCreationTime,
[out] LPFILETIME lpExitTime,
[out] LPFILETIME lpKernelTime,
[out] LPFILETIME lpUserTime
其参数如下:
其返回值和函数说明如下:
相关示例程序如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>
#include <winnt.h>
#include <winternl.h>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
void test_GetProcessTimes()
HANDLE processHandle = GetCurrentProcess();
DWORD currentProcessId = GetProcessId(processHandle);
FILETIME createTime, exitTime, kernelTime, userTime;
DWORD pid = GetCurrentProcessId();
printf("pid: %d\t currentProcessId: %d\n", pid, currentProcessId);
GetProcessTimes(processHandle, &createTime, &exitTime, &kernelTime, &userTime);
printf("processHandle: %lu\t currentProcessId: %d\n", HandleToULong(processHandle), currentProcessId);
printf("Create time: %lu\t %lu\nExit Time: %lu\t %lu\nKernel time: %lu\t %lu\nUser time: %lu\t %lu\n",
createTime.dwLowDateTime, createTime.dwHighDateTime,
exitTime.dwLowDateTime, exitTime.dwHighDateTime,
kernelTime.dwLowDateTime, kernelTime.dwHighDateTime,
userTime.dwLowDateTime, userTime.dwHighDateTime);
::CloseHandle(processHandle);
double get_uptime_sec(DWORD pid)
double r{ 0 };
HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (hProcess)
FILETIME creationTime, exitTime, kernelTime, userTime;
if (::GetProcessTimes(
hProcess, &creationTime, &exitTime, &kernelTime, &userTime)) {
LARGE_INTEGER tCreate;
tCreate.LowPart = creationTime.dwLowDateTime;
tCreate.HighPart = creationTime.dwHighDateTime;
std::cout << "tCreate: " << tCreate.QuadPart << std::endl;
int64_t tt = (static_cast<int64_t>(creationTime.dwHighDateTime) << 32) | creationTime.dwLowDateTime;
std::cout << "tt: " << tt << std::endl;
SYSTEMTIME stCreate;
FileTimeToSystemTime(&creationTime, &stCreate);
r = (double)stCreate.wHour * 3600.0 +
(double)stCreate.wMinute * 60.0 +
(double)stCreate.wSecond +
(double)stCreate.wMilliseconds / 1000.0;
std::cout << "r: " << r << std::endl;
::CloseHandle(hProcess);
return r;
由于GetProcessTimes 函数可以获取某个进程的在内核模式下执行的时间量和用户模式下执行的时间量(以100纳秒为单位)。我们可以先使用NtQuerySystemInformation
函数获取每个CPU核心的总的用户态、内核态、空闲时间总时间量sysTotalTime,然后遍历枚举当前系统所有运行进程,再用GetProcessTimes
去获取每个进程的在内核模式下执行的时间量和用户模式下执行的时间量,除以sysTotalTime即为该进程的CPU使用率。开一个线程每隔一段时间,比如说250毫秒、500毫秒、1秒、2秒等定时轮询获取。
参考ProcessHacker
的源代码,它里面也大体是这个思路。
原文链接http://www.codeproject.com/Articles/4357/GetProcessTimes (需翻墙) 作者:DavidCrow Software Developer (Senior) Pinnacle Business Systems 这么一篇好文被墙掉实在可惜,先粗劣地转过来。点原文链接更精彩= =
Introduction
This a...
主要就是GetProcessTimes和GetThreadTimes这两个函数,它们获得的时间都是FILETIME,下面的程序包含了获得两个FILETIME的差(ms)的办法。
如果要显示FILETIME,可以用FileTimeToSystemTime这个函数(http://msdn.microsoft.com/en-us/library/windows/desktop/ms724280(v=v...
AreYook:
热设计功耗(TDP)与功耗(P)
qq_44652332: