标签:
昨天接到临时任务,需要将一个工作线程执行真正工作的时机推迟到CPU空闲时执行。当时第一感觉认为是将线程优先级设置为空闲级别就行了,以为只有CPU空闲下来才会去跑这个线程,实际上应该不是,毕竟即时是空闲级别也需要排入队列,只不过优先级低而已。当然其实也不能说CPU空闲时来执行,应该说使用率比较低的时候来执行比较合适。
参考博客:http://www.cnblogs.com/TenosDoIt/p/3242910.html,描述了比较多的方法来介绍如何计算CPU使用率。
我尝试了两种方式,使用VS的pdh来计算好像不是很准,但是使用GetSystemTimers来计算基本和任务管理器中显示的很接近了,这里接下这段代码:
// CpuRate.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <Windows.h> #include <cstdio> #include <conio.h> class CCPUUseRate { public: BOOL Initialize() { FILETIME ftIdle, ftKernel, ftUser; BOOL flag = FALSE; if (flag = GetSystemTimes(&ftIdle, &ftKernel, &ftUser)) { m_fOldCPUIdleTime = FileTimeToDouble(ftIdle); m_fOldCPUKernelTime = FileTimeToDouble(ftKernel); m_fOldCPUUserTime = FileTimeToDouble(ftUser); } return flag; } //调用Initialize后要等待1左右秒再调用此函数 int GetCPUUseRate() { int nCPUUseRate = -1; FILETIME ftIdle, ftKernel, ftUser; if (GetSystemTimes(&ftIdle, &ftKernel, &ftUser)) { double fCPUIdleTime = FileTimeToDouble(ftIdle); double fCPUKernelTime = FileTimeToDouble(ftKernel); double fCPUUserTime = FileTimeToDouble(ftUser); nCPUUseRate= (int)(100.0 - (fCPUIdleTime - m_fOldCPUIdleTime) / (fCPUKernelTime - m_fOldCPUKernelTime + fCPUUserTime - m_fOldCPUUserTime) *100.0); m_fOldCPUIdleTime = fCPUIdleTime; m_fOldCPUKernelTime = fCPUKernelTime; m_fOldCPUUserTime = fCPUUserTime; } return nCPUUseRate; } private: double FileTimeToDouble(FILETIME &filetime) { return (double)(filetime.dwHighDateTime * 4.294967296E9) + (double)filetime.dwLowDateTime; } private: double m_fOldCPUIdleTime; double m_fOldCPUKernelTime; double m_fOldCPUUserTime; }; int main() { do { CCPUUseRate cpuUseRate; if (!cpuUseRate.Initialize()) { printf("WorkThread :初始化系统使用时间失败,错误码%d", GetLastError()); break; } while (true) { Sleep(1000); int liCpuUserRate = cpuUseRate.GetCPUUseRate(); printf("\r当前CPU使用率为:%4d%%", liCpuUserRate); } } while (false); return 0; }
标签:
原文地址:http://www.cnblogs.com/monotone/p/4241893.html