解法一
int main()
{
for(; ; )
{
for(int i = 0; i < 9600000; i++)
;
Sleep(10);
}
return 0;
}
解法二:使用gettickcount()和sleep()
int busyTime = 10; // 10 ms
int idleTime = busyTime; // same ratio will lead to 50% cpu usage
Int64 startTime = 0;
while(true)
{
startTime = GetTickCount();
// busy loop
while((GetTickCount() - startTime) <= busyTime)
;
// idle loop
Sleep(idleTime);
}
解法三:动态适应
int busyTime = 10; // 10 ms
int idleTime = busyTime; // same ratio will lead to 50% cpu usage
Int64 startTime = 0;
while(true)
{
startTime = GetTickCount();
// busy loop
while((GetTickCount() - startTime) <= busyTime)
;
// idle loop
Sleep(idleTime);
}
解法四:正弦曲线
// C++ code to make task manager generate sine graph
#include "Windows.h"
#include "stdlib.h"
#include "math.h"
const double SPLIT = 0.01;
const int COUNT = 200;
const double PI = 3.14159265;
const int INTERVAL = 300;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD busySpan[COUNT]; // array of busy times
DWORD idleSpan[COUNT]; // array of idle times
int half = INTERVAL / 2;
double radian = 0.0;
for(int i = 0; i < COUNT; i++)
{
busySpan[i] = (DWORD)(half + (sin(PI * radian) * half));
idleSpan[i] = INTERVAL - busySpan[i];
radian += SPLIT;
}
DWORD startTime = 0;
int j = 0;
while(true)
{
j = j % COUNT;
startTime = GetTickCount();
while((GetTickCount() - startTime) <= busySpan[j])
;
Sleep(idleSpan[j]);
j++;
}
return 0;
}
解法五:多cpu
inline __int64 GetCPUTickCount()
{
__asm
{
rdtsc;
}
}
_PROCESSOR_POWER_INFORMATION info;
CallNTPowerInformation(11, // query processor power information
NULL, // no input buffer
0, // input buffer size is zero
&info, // output buffer
Sizeof(info)); // outbuf size
__int64 t_begin = GetCPUTickCount();
// do something
__int64 t_end = GetCPUTickCount();
double millisec = ((double)t_end –
(double)t_begin)/(double)info.CurrentMhz;
1.Sleep()——这个方法能让当前线程“停”下来。
2.WaitForSingleObject()——自己停下来,等待某个事件发生。
3.GetTickCount()——有人把Tick翻译成“嘀嗒”,很形象。
4.QueryPerformanceFrequency()、QueryPerformanceCounter()——让你访问到精度更高的CPU数据。
5.timeGetSystemTime()——是另一个得到高精度时间的方法。
6.PerformanceCounter——效能计数器。
7.GetProcessorInfo()/SetThreadAffinityMask()。——遇到多核问题时,这个函数帮你控制cpu
8.GetCPUTickCount()。——想拿到CPU核心运行周期函数吗?用用这个方法吧