注释掉的部分是单线程版本,如果是双核的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; //设置CPU数量
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);
}
}