一、程序实现单核CPU画图
可能是系统原因、某个CPU跑几秒后就转移到另一个CPU上跑。
单个程序画图时都采用的 手动设置相关性。
1.1 百分百全占用
#include <stdio.h>
int main()
{
while (1)
{
}
return 0;
}
1.2. 50%占用
不让程序畅通无阻
//二分答案
#include <stdio.h>
#include <Windows.h>
const long long n = 1e7;
int main()
{
while (1)
{
for (int i = 0; i < n; ++i);
Sleep(10);
}
return 0;
}
1.3. 直上直下
让程序多歇会儿
#include <stdio.h>
#include <Windows.h>
const long long n = 7e8;
int main()
{
while (1)
{
for (int i = 0; i < n; ++i);
Sleep(1000);
}
return 0;
}
1.4. 类sin函数
Sleep
的作用是将时间切片
//clock() : 1500 1.5秒的样子
#include <windows.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
clock_t sta, tmp;
int main()
{
sta = clock(); //初始时间点
//每次计算运行多少次
while (1)
{
tmp = clock();
double x = (tmp - sta) / CLK_TCK;
int y = 1e8 + sin(x) * 1e8;
for (int i = 0; i < y; ++i);
Sleep(90);
}
return 0;
}
二、将这些图拼到一个程序中
一开始搜的“CPU亲和性” “windows控制CPU” 之类的关键字,没有找到想要的答案。
后来顺藤摸瓜搜“线程句柄”。在别人的源码上做了些修改完成了代码。
#include<process.h>
#include<windows.h>
#include<thread>
#include<iostream>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
using namespace std;
unsigned int __stdcall f1(PVOID pM)
{
GetCurrentThreadId(); //重点!
while (1)
{
}
return 0;
}
unsigned int __stdcall f2(PVOID pM)
{
GetCurrentThreadId();
int n = 1e7;
while (1)
{
for (int i = 0; i < n; ++i);
Sleep(10);
}
return 0;
}
unsigned int __stdcall f3(PVOID pM)
{
GetCurrentThreadId();
int n = 7e8;
while (1)
{
for (int i = 0; i < n; ++i);
Sleep(1000);
}
return 0;
}
unsigned int __stdcall f4(PVOID pM)
{
GetCurrentThreadId();
clock_t sta, tmp;
sta = clock(); //初始时间点
//每次计算运行多少次
while (1)
{
tmp = clock();
double x = (tmp - sta) / CLK_TCK;
int y = 1e8 + sin(x) * 1e8;
for (int i = 0; i < y; ++i);
Sleep(90);
}
return 0;
}
int main()
{
const int THREAD_NUM = 8;
HANDLE handle[THREAD_NUM];
unsigned long mask;
handle[0] = (HANDLE)_beginthreadex(NULL, 0, f1, NULL, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask(handle[0], 1 << 0); //重点!!
handle[1] = (HANDLE)_beginthreadex(NULL, 0, f2, NULL, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask(handle[1], 1 << 1);
handle[2] = (HANDLE)_beginthreadex(NULL, 0, f3, NULL, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask(handle[2], 1 << 2);
handle[3] = (HANDLE)_beginthreadex(NULL, 0, f4, NULL, CREATE_SUSPENDED, NULL);
SetThreadAffinityMask(handle[3], 1 << 3);
for (int i = 0; i < 6; ++i)
{
int x; cin >> x;
ResumeThread(handle[x]);
}
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
system("pause");
return 0;
}
关于最后的程序小结:
- GetCurrentThreadId(); 创建一个线程句柄
- SetThreadAffinityMask 不能忘写!!作用是绑定CPU