C#, ロジック
- CPUパフォーマンス
現在のCPUパフォーマンスを%で返します。GetNextメソッドを定期的に呼び出してください。
/// <summary>CPUパフォーマンスモニタ</summary>
public class PerformanceCpu
{
/// <summary>CPU使用量(%)</summary>
public int Value
{
get
{
return _nValue;
}
}
private int _nValue;
private System.Diagnostics.PerformanceCounter _performanceCounter;
private DateTime _prevTime;
private TimeSpan _prevProcTime;
private System.Diagnostics.Process _process;
/// <summary>Constructor</summary>
public PerformanceCpu()
{
}
/// <summary>初期化</summary>
public void Initialize()
{
Initialize( null );
}
/// <summary>初期化</summary>
/// <param name="process">監視するプロセス(NULLの時は全プロセス)</param>
public void Initialize( System.Diagnostics.Process process )
{
_process = process;
_performanceCounter = new System.Diagnostics.PerformanceCounter();
_performanceCounter.CategoryName = "Processor";
_performanceCounter.CounterName = "% Processor Time";
if( process == null )
{
_performanceCounter.InstanceName = "_Total";
}
else
{
_performanceCounter.InstanceName = process.ProcessName;
}
}
/// <summary>To get next performance</summary>
/// <returns>CPU使用量(%)</returns>
public int GetNext()
{
_nValue = -1;
try
{
double dNextValue = -1;
if( _process == null )
{
dNextValue = _performanceCounter.NextValue();
}
else
{
DateTime dtNow = DateTime.Now;
TimeSpan newPrcTime = _process.TotalProcessorTime;
TimeSpan cmpTime = dtNow.Subtract( _prevTime );
TimeSpan prcTimeSpan = newPrcTime.Subtract( _prevProcTime );
if( newPrcTime.TotalMilliseconds == 0 ) return -1;
dNextValue = ( prcTimeSpan.TotalMilliseconds * 1000 / cmpTime.TotalMilliseconds ) / 10;
// For Next
_prevTime = dtNow;
_prevProcTime = newPrcTime;
}
_nValue = ( int )dNextValue;
}
catch( Exception ex )
{
_nValue = -1;
Console.WriteLine( this.GetType().Name + ":" + ex.Message );
}
return _nValue;
}
}