注意(不是我的代码):SOURCE Sayyed Mohsen Zahraee制作的页面底部。我在我的帖子中做了一些小的改动,但他的原始代码可以立即使用。
在尝试查看此代码的工作原理时,我还试图找到一种方法来获得最终输出,当通过if语句遇到某个参数时,触发一个动作。
#include <iostream>
#include <windows.h>
#include <stdio.h>
void GetSystemTimesAddress();
CHAR cpuusage();
int main(void)
{
int n;
GetSystemTimesAddress();
for(n=0;n<20;n++)
{
printf("CPU Usage: %3d%%\r",cpuusage());
Sleep(2000);
if ((printf("%3d%%\r",cpuusage())) = '10')//Doesn't work but goal action
{
std::cout << "just fine";
}
if ((printf("%3d%%\r",cpuusage())) = '30')
{
std::cout << "keep an eye on";
}
if ((printf("%3d%%\r",cpuusage())) = '50')
{
std::cout << "getting warm";
}
if ((printf("%3d%%\r",cpuusage())) = '70')
{
std::cout << "pretty dangerous";
}
}
printf("\n");
return 0;
}
//Bellow CPU usage meathods
CHAR cpuusage(void);
typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;
static HMODULE s_hKernel = NULL;
void GetSystemTimesAddress()
{
if( s_hKernel == NULL )
{
s_hKernel = LoadLibrary( L"Kernel32.dll" );
if( s_hKernel != NULL )
{
s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress( s_hKernel, "GetSystemTimes" );
if( s_pfnGetSystemTimes == NULL )
{
FreeLibrary( s_hKernel ); s_hKernel = NULL;
}
}
}
}
// cpuusage(void)
// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
CHAR cpuusage()
{
FILETIME ft_sys_idle;
FILETIME ft_sys_kernel;
FILETIME ft_sys_user;
ULARGE_INTEGER ul_sys_idle;
ULARGE_INTEGER ul_sys_kernel;
ULARGE_INTEGER ul_sys_user;
static ULARGE_INTEGER ul_sys_idle_old;
static ULARGE_INTEGER ul_sys_kernel_old;
static ULARGE_INTEGER ul_sys_user_old;
CHAR usage = 0;
// we cannot directly use GetSystemTimes on C language
/* add this line :: pfnGetSystemTimes */
s_pfnGetSystemTimes(&ft_sys_idle, /* System idle time */
&ft_sys_kernel, /* system kernel time */
&ft_sys_user); /* System user time */
CopyMemory(&ul_sys_idle , &ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_user , &ft_sys_user , sizeof(FILETIME)); // Could been optimized away...
usage =
(
(
(
(
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
)
-
(ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
)
*
(100)
)
/
(
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
)
);
ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;
ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;
ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;
return usage;
}
如果有人找到了让if staments工作的方法,你能不能简单解释一下它是如何工作的。我理解这样的事情在一两个简单的段落中难以解释,但即使是简单的事情也是一个很好的学习机会。谢谢!
答案 0 :(得分:1)
当你想要比较时,你分配。这是Stack上常见的问题。您还试图比较printf
返回的内容。此外,你正在努力用两个角色制作一个角色。 '10'
无效。它可能是一个C字符串,"10"
,但很可能你想要一个int
。更改if的来自:
if ((printf("%3d%%\r",cpuusage())) = '10')
要
if(cpuusage() == 10)