编程之美 1.1、CPU占用率

来源:互联网 发布:英语视频软件app 编辑:程序博客网 时间:2024/05/16 12:18

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;//PerformanceCounterusing System.Threading;//PerformanceCounterusing System.Collections;//PerformanceCounternamespace 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);        }    }}


 

原创粉丝点击