PerformanceCounter
从编写程序控制cpu占用率说起:
考虑:任务管理器每一秒钟刷新一次,要在这一秒钟内,使CPU的平均使用时间和空闲时间各占50%.而不是让CPU使用1秒钟,空闲一秒钟。这样的话任务管理器出现的CPU的使用图像会是忽高忽低。windows的调度时间片为10ms,所以在编写程序的时候就可以让cpu不停的工作10ms,然后空闲10ms,空闲操作通过sleep(10)来实现。这样最后任务管理器在刷新CPU占用率的时候就会得到这个一秒钟内的CPU的平均使用率。显示出50%的水平。
通过空循环,来让cpu保持繁忙的工作状态,通过sleep使cpu空闲。
考虑到我的电脑的主频是2.0G,所以应该是每秒可以执行2000000000*2/5=800000000条空循环。然而不能让机器执行一秒的空循环,应该分时间片的执行。一个时间片10ms,所以执行空循环应该为8000000次。
#include
#include
intmain(intargc,char*argv[])
{
longn=8000000;
inti=0;
while(1)
{
for(i=0;i
{
//idle
}
sleep(10);
}
system("PAUSE");
return0;
}
http://blog.csdn.net/weixingstudio/article/details/6865775
上述程序经验证在windows下可用,在linux下因为调度算法优化等问题,暂时不可用!!或许通过修改设置linux的调度算法可以达到此目的.
Windows下Sleep(10)
而linux下是sleep(10)而且要include
除此外,通过调用系统的GetTickCount()函数可以获得系统启动到现在的时间值,通过这个时间值也可以控制系统的繁忙的时间片和空闲的时间片。让系统一个时间片不停地做循环,一个时间片做休眠,这样一秒钟以后品均下来也可以让CPU的占用率接近50%。
//cpu_2.cpp:Definestheentrypointfortheconsoleapplication.
//
#include"stdafx.h"
#include"windows.h"
int_tmain(intargc,_TCHAR*argv[])
{
constDWORDbusyTime=10;
constDWORDidleTime=busyTime;
DWORDstartTime=GetTickCount();
while(true)
{
startTime=GetTickCount();
while(GetTickCount()-startTime<=busyTime)
{
//IDLE
}
Sleep(idleTime);
}
return0;
}
MS.NETFRAMEWORK还提供了PerformanceCounter这一对象,可以获得系统资源的各种性能数据,通过这个PerformanceCounter对象,我们可以更准确的获得CPU的信息。
PerformanceCounterpc=newPerformanceCounter(CategoryName,CounterName,InstanceName);
表示WindowsNT性能计数器组件
命名空间:System.DiagnosticsC#
程序集:System(在system.dll中)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Diagnostics;
namespacecpu_3_csharp
{
classProgram
{
staticvoidMain(string[]args)
{
floatlevel=150F;
PerformanceCounterCategory[]test=PerformanceCounterCategory.GetCategories();
for(inti=0;i<test.Length;i++)
{
//Console.WriteLine(test[i].CategoryName);
if(test[i].CategoryName=="Processor")
{
string[]temp=test[i].GetInstanceNames();
//Console.WriteLine(temp.Length);
for(intj=0;j<temp.Length;j++)
{
Console.WriteLine(test[i].MachineName);
Console.WriteLine("------------------------");
Console.WriteLine(temp[j]);
Console.WriteLine("------------------------");
PerformanceCounter[]counters=test[i].GetCounters(temp[j]);
for(intk=0;k<counters.Length;k++)
{
Console.WriteLine(counters[k].CounterName);
}
}
}
}
Console.WriteLine("*******************************************************");
PerformanceCounterp=newPerformanceCounter("Processor","%ProcessorTime","_Total");
Console.WriteLine(p.NextValue());
while(true)
{
//Console.WriteLine(p.NextValue());
if(p.NextValue()>level)
{
System.Threading.Thread.Sleep(10);
}
}
}
}
}
http://www.cnblogs.com/xh831213/archive/2008/06/12/1218234.html
http://www.codeproject.com/Articles/8590/An-Introduction-To-Performance-Counters
上述给出了在visualstadio下查看PerformanceCounter的方法,server-explorer
另一个代码C++:
#using
usingnamespaceSystem;
usingnamespaceSystem::Collections;
usingnamespaceSystem::Collections::Specialized;
usingnamespaceSystem::Diagnostics;
//Outputinformationaboutthecountersample.
voidOutputSample(CounterSamples)
{
Console::WriteLine("rn+++++++++++");
Console::WriteLine("Samplevalues-rn");
Console::WriteLine("BaseValue={0}",s.BaseValue);
Console::WriteLine("CounterFrequency={0}",s.CounterFrequency);
Console::WriteLine("CounterTimeStamp={0}",s.CounterTimeStamp);
Console::WriteLine("CounterType={0}",s.CounterType);
Console::WriteLine("RawValue={0}",s.RawValue);
Console::WriteLine("SystemFrequency={0}",s.SystemFrequency);
Console::WriteLine("TimeStamp={0}",s.TimeStamp);
Console::WriteLine("TimeStamp100nSec={0}",s.TimeStamp100nSec);
Console::WriteLine("++++++++++++++++++++++");
}
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//Description-Thiscountertypeshowshowmanyitemsareprocessed,onaverage,
//duringanoperation.Countersofthistypedisplayaratiooftheitems
//processed(suchasbytessent)tothenumberofoperationscompleted.The
//ratioiscalculatedbycomparingthenumberofitemsprocessedduringthe
//lastintervaltothenumberofoperationscompletedduringthelastinterval.
//Generictype-Average
//Formula-(N1-N0)/(D1-D0),wherethenumerator(N)representsthenumber
//ofitemsprocessedduringthelastsampleintervalandthedenominator(D)
//representsthenumberofoperationscompletedduringthelasttwosample
//intervals.
//Average(Nx-N0)/(Dx-D0)
//ExamplePhysicalDiskAvg.DiskBytes/Transfer
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
floatMyComputeCounterValue(CounterSamples0,CounterSamples1)
{
floatnumerator=(float)s1.RawValue-(float)s0.RawValue;
floatdenomenator=(float)s1.BaseValue-(float)s0.BaseValue;
floatcounterValue=numerator/denomenator;
returncounterValue;
}
boolSetupCategory()
{
if(!PerformanceCounterCategory::Exists("AverageCounter64SampleCategory"))
{
CounterCreationDataCollection^CCDC=gcnewCounterCreationDataCollection;
//Addthecounter.
CounterCreationData^averageCount64=gcnewCounterCreationData;
averageCount64->CounterType=PerformanceCounterType::AverageCount64;
averageCount64->CounterName="AverageCounter64Sample";
CCDC->Add(averageCount64);
//Addthebasecounter.
CounterCreationData^averageCount64Base=gcnewCounterCreationData;
averageCount64Base->CounterType=PerformanceCounterType::AverageBase;
averageCount64Base->CounterName="AverageCounter64SampleBase";
CCDC->Add(averageCount64Base);
//Createthecategory.
PerformanceCounterCategory::Create("AverageCounter64SampleCategory","DemonstratesusageoftheAverageCounter64performancecountertype.",CCDC);
return(true);
}
else
{
Console::WriteLine("Categoryexists-AverageCounter64SampleCategory");
return(false);
}
}
voidCreateCounters(PerformanceCounter^%PC,PerformanceCounter^%BPC)
{
//Createthecounters.
PC=gcnewPerformanceCounter("AverageCounter64SampleCategory","AverageCounter64Sample",false);
BPC=gcnewPerformanceCounter("AverageCounter64SampleCategory","AverageCounter64SampleBase",false);
PC->RawValue=0;
BPC->RawValue=0;
}
voidCollectSamples(ArrayList^samplesList,PerformanceCounter^PC,PerformanceCounter^BPC)
{
Random^r=gcnewRandom(DateTime::Now.Millisecond);
//Loopforthesamples.
for(intj=0;j<100;j++)
{
intvalue=r->Next(1,10);
Console::Write("{0}={1}",j,value);
PC->IncrementBy(value);
BPC->Increment();
if((j%10)==9)
{
OutputSample(PC->NextSample());
samplesList->Add(PC->NextSample());
}
else
Console::WriteLine();
System::Threading::Thread::Sleep(50);
}
}
voidCalculateResults(ArrayList^samplesList)
{
for(inti=0;i<(samplesList->Count-1);i++)
{
//Outputthesample.
OutputSample(*safe_cast(samplesList[i]));
OutputSample(*safe_cast(samplesList[i+1]));
//Use.NETtocalculatethecountervalue.
Console::WriteLine(".NETcomputedcountervalue={0}",CounterSampleCalculator::ComputeCounterValue(*safe_cast(samplesList[i]),*safe_cast(samplesList[i+1])));
//Calculatethecountervaluemanually.
Console::WriteLine("Mycomputedcountervalue={0}",MyComputeCounterValue(*safe_cast(samplesList[i]),*safe_cast(samplesList[i+1])));
}
}
intmain()
{
ArrayList^samplesList=gcnewArrayList;
PerformanceCounter^PC;
PerformanceCounter^BPC;
SetupCategory();
CreateCounters(PC,BPC);
CollectSamples(samplesList,PC,BPC);
CalculateResults(samplesList);
}
http://msdn.microsoft.com/zh-cn/library/system.diagnostics.performancecounter(v=vs.80).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-4