1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| static ManagementObjectSearcher WMIProcessorSearcher { get; set; }
static ManagementScope WMILocalScope { get; set; }
static List<LastCPUInfos> LastCPUs { get; set; }
protected class LastCPUInfos
{
public virtual ulong ProcessorTime { get; set; }
public virtual ulong SysTimeStamp { get; set; }
public virtual double ProcessorUsage { get; set; }
}
private static void ShowCPU()
{
LastCPUs = new List<LastCPUInfos>();
WMILocalScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", Environment.MachineName));
WMIProcessorSearcher = new ManagementObjectSearcher(WMILocalScope,
new SelectQuery("Win32_PerfRawData_PerfOS_Processor"));
ulong current_time = 0;
ulong sys_time = 0;
int index = 0;
ManagementObjectCollection result = null;
double total_processor_usages = 0;
while (true)
{
total_processor_usages = 0;
index = 0;
result = WMIProcessorSearcher.Get();
foreach (ManagementBaseObject obj in result)
{
if ((obj["Name"] as string) == "_Total")
continue;
else
{
current_time = (ulong)obj["PercentProcessorTime"];
sys_time = (ulong)obj["TimeStamp_Sys100NS"];
if (LastCPUs.Count <= index)
{
LastCPUs.Add(new LastCPUInfos()
{
ProcessorTime = current_time,
SysTimeStamp = sys_time
});
}
else
{
if (sys_time - LastCPUs[index].SysTimeStamp > 0) /* Bah ouais, ou sinon Division par zéro -> BOOM */
{
LastCPUs[index].ProcessorUsage = 1.0 - ((double)(current_time - LastCPUs[index].ProcessorTime) / (double)(sys_time - LastCPUs[index].SysTimeStamp));
total_processor_usages += LastCPUs[index].ProcessorUsage;
}
LastCPUs[index].ProcessorTime = current_time;
LastCPUs[index].SysTimeStamp = sys_time;
Console.WriteLine(String.Format("Coeur {0} : {1}", index, LastCPUs[index].ProcessorUsage));
}
index++;
}
}
if (index > 0)
{
Console.WriteLine(String.Format("Utilisation moyenne : {0}", total_processor_usages / index));
}
System.Threading.Thread.Sleep(1000);
}
} |
Partager