Windows API :
Sleep();让线程停下来
GetTickCount();获取当前系统时间
PerformanceCounter();效能计数器
GetCPUTickCount();获取CPU核心运行周期数
GetProcessorInfo()/SetThreadAffinityMask();多核问题,控制CPU
timeGetSystemTime();获取高精度时间的方法。
WaitForSingleObject();自己停下来等待某件事情发生。
一、系统中只有当前实例在运行。CPU50% 。windows.h中有GetTickCount()函数,用于记录当前从系统中获取的时间。
#include<iostream> #include<Windows.h> using namespace std; int main() { const int busyTime=10; const int idleTime=busyTime; long int startTime=0; while (true) { startTime=GetTickCount(); while ((GetTickCount()-startTime)<=busyTime) { ; } Sleep(idleTime); } return 0; }
二、动态适应的方法、PerformanceCounter是效能计数器。多个进程占用CPU
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics;//PerformanceCounter using System.Threading;//PerformanceCounter using System.Collections;//PerformanceCounter namespace ConsoleApplication1 { class Program { static void MakeUsage(float level) { PerformanceCounter p = new PerformanceCounter("Processor", "% Processor Time", "_Total"); while (true) { if (p.NextValue()>level) { System.Threading.Thread.Sleep(10); System.Console.Write("huahua\n"); } } } static void Main(string[] args) { MakeUsage(20); } } }