一、.相关函数
1.time_t time(time_t* t);获取机器时间。该函数获取当前距1970年1月1日00:00:00所经历的时间(单位:秒)。包含在头文件<time.h>中。
2.void Sleep(DWORD d);让机器休眠一段时间d(单位:毫秒)。包含在头文件<windows.h>中。
3.DWORD GetTickCount(VOID);获取系统从启动到现在所经历的时间(单位:毫秒),包含在头文件<windows.h>中。
4.void GetSystemInfo(LPSYSTEM_INFO);获取硬件信息。
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
printf("Hardware information:\n");
printf("OEM ID:%u\n",sys_info.dwOemId);
printf("Number of Processors:%u\n",sys_info.dwNumberOfProcessors);
printf("Processor type:%u\n",sys_info.dwProcessorType);
printf("Minimum application address:%lx\n",sys_info.lpMinimumApplicationAddress);
printf("Maximum application address:%lx\n",sys_info.lpMaximumApplicationAddress);
printf("Active process mask:%u\n",sys_info.dwActiveProcessorMask);
5.DWORD SetThreadAffinityMask(HANDLE,DWORD);指定进程在某个处理器上运行。
如:
SetThreadAffinityMask(thread1, 0x01<<0);//线程1运行在第一个处理器上
SetThreadAffinityMask(thread2, 0x01<<1);//线程2运行在第二个处理器上
SetThreadAffinityMask(thread3, 0x01<<2);//线程3运行在第三个处理器上
SetThreadAffinityMask(thread4, 0x01<<3);//线程4运行在第四个处理器上
二、代码验证
1、CPU使用率50%
运行时间与休眠时间各占一半。代码如下:
#include <time.h>
#include <windows.h>
const DWORD busyTime=100;
const DWORD idleTime=busyTime;
__int64 startTime=0;
int main()
{
SetThreadAffinityMask(GetCurrentThread(), 8);
while(true)
{
DWORD startTime=GetTickCount();
while((GetTickCount()-startTime)<=busyTime);
Sleep(idleTime);
}
return 0;
}
运行结果如下图:
程序运行在第4个处理器上,占用率有点偏高,应该是因为有其他进程在该处理器上运行。
2.占用率呈sin曲线
设置程序运行与休眠的时间,总时间片恒定,使运行时间呈sin曲线对应的值变化,剩下的时间休眠,可得到CPU占用率呈现sin曲线。代码如下(附详细注释):
#include <stdio.h>
#include <math.h>
#include <windows.h>
#include <time.h>
const int SAMPLING_COUNT=200;//200个抽样点
const double PI=3.1415926535;
const int TOTAL_AMPLITUDE=300;//每个抽样点对应的时间片,运行时间+休眠时间=300ms
int main()
{
SetThreadAffinityMask(GetCurrentThread(), 8);//进程运行在第4个处理器上
DWORD busySpan[SAMPLING_COUNT] ;//程序运行时间存储在此
int amplitude=TOTAL_AMPLITUDE/2;//将sin曲线整体提高 TOTAL_AMPLITUDE/2,避免负值出现
double radian=0.0;//初始弧度
double radianIncrement=(2.0*PI)/(double)SAMPLING_COUNT;//每次增加radianIncrement得到新的弧度值
for(int i=0;i<SAMPLING_COUNT;i++)//将SAMPLING_COUNT个抽样点对应的sin值写入数组busySpan中,以便调用
{
busySpan[i]=(DWORD)(amplitude+sin(radian)*amplitude);
radian+=radianIncrement;
}
DWORD startTime=0;
int j=0;
for(j=0;;j=(j+1)%SAMPLING_COUNT)
{
startTime=GetTickCount();
while((GetTickCount()-startTime) <= busySpan[j]);//运行busySpan[j]长度的时间
Sleep(TOTAL_AMPLITUDE-busySpan[j]);//休眠时间=总时间-运行时间
}
return 0;
}
运行结果如下图:
进程运行在第四个处理器上。CPU使用率呈sin曲线。