注釋掉的部分是單線程版本,如果是雙核的CPU,那么CPU使用率峰值在50%左右,因為有其他程序運行,所以可能會有點影響
考慮到雙核或者多核,于是使用多線程,主線程直接Sleep
先上截圖


下面是代碼
作者:Gods_巨蟻(博主)
#include <windows.h>
#include <cmath>
#include <process.h> //for 多線程
using namespace std;
/*
void DoSth(unsigned iDelay)
{
unsigned iStart = ::GetTickCount();
while(::GetTickCount() - iStart < iDelay);
}
int main() //單核情況
{
double x = 0.0;
double y;
while(1)
{
y = sin(x);
unsigned iDelay = static_cast<int>(500 * y) + 500;
DoSth(iDelay);
Sleep(1000 - iDelay);
x += 0.314;
if(x >= 6.28)
x = 0;
}
}
*/
unsigned __stdcall mtThreadDoSth(void * param)
{
unsigned iDelay = reinterpret_cast<int>(param);
int iStart = ::GetTickCount();
while(::GetTickCount() - iStart < iDelay);
return 0;
}
//多核情況
int main(int argc, char **argv)
{
unsigned long thd;
unsigned tid;
int cCpus = 2; //設(shè)置CPU數(shù)量
double x = 0.0;
double y;
while(1)
{
y = sin(x);
unsigned iDelay = static_cast<int>(500 * y) + 500;
for(int i = 0; i < cCpus; ++i)
{
thd = _beginthreadex(NULL,
0,
mtThreadDoSth,
(void *)iDelay,
0,
&tid);
if(thd != NULL){
CloseHandle((HANDLE)thd);
}
}
x += 0.314;
if(x >= 6.28)
x = 0;
Sleep(1000);
}
}