Skip to content

Instantly share code, notes, and snippets.

@wtarr
Created July 24, 2013 11:48
Show Gist options
  • Save wtarr/6069861 to your computer and use it in GitHub Desktop.
Save wtarr/6069861 to your computer and use it in GitHub Desktop.
VBS -> C# translation of http://msdn.microsoft.com/en-us/library/windows/desktop/aa394317%28v=vs.85%29.aspx determine number socket / cores and display percent processor load for each core and total for the socket.
using System;
using System.Management;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
string totalcore = "";
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
var iSocket = 1;
foreach (ManagementObject objProcessor in searcher.Get())
{
var iNumLogicalProcessors = int.Parse(objProcessor["NumberOfLogicalProcessors"].ToString());
var iNumCores = int.Parse(objProcessor["NumberOfCores"].ToString());
var architecture = "";
if (iNumCores > 1)
{
architecture = iNumLogicalProcessors > iNumCores ? "MULTICOREHT" : "MULTICORE";
}
else
{
architecture = iNumLogicalProcessors > iNumCores ? "SINGLECOREHT" : "SINGLECORE";
}
var innerSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");
var innerSearcherCollection = innerSearcher.Get();
var iHypThdModule = 1;
var iCore = 1;
var iTotalHypThdModule = (innerSearcherCollection.Count - 1)/iNumCores;
foreach (var objPref in innerSearcherCollection)
{
if (!objPref["Name"].ToString().Equals("_Total"))
{
switch (architecture)
{
case "MULTICOREHT":
Console.WriteLine("Multicore Hyper Threading");
Console.WriteLine("Socket " + iSocket + " Core: " + iCore + " HT Module " + iHypThdModule);
Console.WriteLine("Percentage Processor Load: " + objPref["PercentProcessorTime"]);
iHypThdModule++;
if (iHypThdModule > iTotalHypThdModule)
{
iHypThdModule = 1;
iCore = iCore + 1;
}
break;
case "SINGLECOREHT":
Console.WriteLine("Single Core Hyper Threading");
Console.WriteLine("Socket: " + iSocket + "Core 1 HT Module " + iHypThdModule);
Console.WriteLine("Percentage Processor Load: " + objPref["PercentProcessorTime"]);
iHypThdModule++;
break;
case "MULTICORE":
Console.WriteLine("Multicore");
Console.WriteLine("Socket: " + iSocket + " Core " + iCore);
Console.WriteLine("Percentage Processor Load: " + objPref["PercentProcessorTime"]);
iCore++;
break;
case "SINGLECORE":
Console.WriteLine("Single Core");
Console.WriteLine("Socket " + iSocket + " Core 1");
Console.WriteLine("Percentage Processor Load: " + objPref["PercentProcessorTime"]);
break;
}
}
else
{
totalcore = objPref["PercentProcessorTime"].ToString();
}
}
iSocket++;
Console.WriteLine("\n\nSocket total " + totalcore);
}
}
catch (ManagementException e)
{
Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment