代码取自《编程之美》
随便找个编译器就可以运行,比如Devcpp等
#include <stdlib.h>
#include <windows.h>
#include <math.h>
const int COUNT = 200;/* 把一个正弦周期平分成 COUNT 份 */
const double SPLIT = 2.0/COUNT;/* 用于后面计算sin值 */
const double PI = 3.1415926;
const int INTERVAL = 300;/* 一个采样周期的时长 */
int main()
{
SetThreadAffinityMask(GetCurrentThread(), 2);/* 指定当前线程在哪个CPU上运行 */
DWORD busySpan[COUNT];/* 记录周期中的每一份的忙碌的时长 */
DWORD idleSpan[COUNT];/* 记录周期中的每一份的空闲的时长 */
int half = INTERVAL / 2;
double radian = 0.0;
for (int i = 0; i < COUNT; ++i)
{
/* 结合half进行运算是为了向上平移正弦函数,保证非负的忙碌时长,且最大值为INTERVAL */
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 += 1;
}
return 0;
}
所以可以随意操控CPU,不管是控制它一直50%还是90%,都可以,只要控制CPU的忙闲时间就好。
多核CPU同时变化
#include <iostream>
#include <windows.h>
#include <cmath>
#define PI 3.1415926535
using namespace std;
const double _1000MILLI = 1000;
void per_second_cpu(__int64 start_time,double busy_time_rate){
start_time = GetTickCount();
while ((GetTickCount() - start_time) <= busy_time_rate * _1000MILLI){}
Sleep((1.0-busy_time_rate) * _1000MILLI);
}
void line_cpu( double busy_time_rate ){
__int64 start_time;
while(true){
per_second_cpu(start_time,busy_time_rate);
}
}
void sin_cpu(){
__int64 start_time;
while(true){
int t = 15;
for (int i = 0; i < t; ++i) {
double busy_time_rate = sin( i * 2 / ( t * 1.0 ) * PI ) / 2.0 + 0.5;
per_second_cpu(start_time , busy_time_rate);
}
}
}
DWORD WINAPI handle_line(LPVOID lpParameter){
line_cpu(*(double*)lpParameter);
}
DWORD WINAPI handle_sin(LPVOID lpParameter){
sin_cpu();
}
void begin_line(double busy_time_rate){
SetProcessAffinityMask(GetCurrentProcess(),255);
for (int i = 0; i < 7; ++i) {
HANDLE handleProcess = CreateThread(NULL, 0, handle_line, &busy_time_rate, 0, NULL);
CloseHandle(handleProcess);
}
line_cpu(busy_time_rate);
}
void begin_sin(){
SetProcessAffinityMask(GetCurrentProcess(),255);
for (int i = 0; i < 7; ++i) {
HANDLE handleProcess = CreateThread(NULL, 0, handle_sin, NULL, 0, NULL);
CloseHandle(handleProcess);
}
sin_cpu();
}
int main() {
// double busy_time_rate=0.5;
// begin_line(busy_time_rate);
begin_sin();
return 0;
}