代碼取自《編程之美》
隨便找個編譯器就可以運行,比如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;
}