-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhysicalCoreTest.cs
More file actions
107 lines (95 loc) · 3.52 KB
/
PhysicalCoreTest.cs
File metadata and controls
107 lines (95 loc) · 3.52 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Management;
using System.Runtime.InteropServices;
namespace PhysicalCoreExperiments
{
class Program
{
static void Main()
{
Console.WriteLine($"Environment.ProcessorCount: {Environment.ProcessorCount}");
// Test different approaches to get physical core count
Console.WriteLine("\n=== Different approaches to get physical cores ===");
try
{
// Approach 1: WMI (Windows only)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
int physicalCores = GetPhysicalCoresWmi();
Console.WriteLine($"Physical cores (WMI): {physicalCores}");
}
// Approach 2: /proc/cpuinfo parsing (Linux)
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
int physicalCores = GetPhysicalCoresLinux();
Console.WriteLine($"Physical cores (Linux): {physicalCores}");
}
// Current approach
int currentApproach = Environment.ProcessorCount / 2;
Console.WriteLine($"Current approach (ProcessorCount/2): {currentApproach}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static int GetPhysicalCoresWmi()
{
int physicalCores = 0;
using (var searcher = new ManagementObjectSearcher("SELECT NumberOfCores FROM Win32_Processor"))
{
foreach (var item in searcher.Get())
{
physicalCores += int.Parse(item["NumberOfCores"].ToString());
}
}
return physicalCores;
}
static int GetPhysicalCoresLinux()
{
try
{
var cpuInfo = System.IO.File.ReadAllText("/proc/cpuinfo");
var lines = cpuInfo.Split('\n');
var physicalIds = new System.Collections.Generic.HashSet<string>();
foreach (var line in lines)
{
if (line.StartsWith("physical id"))
{
var parts = line.Split(':');
if (parts.Length > 1)
{
physicalIds.Add(parts[1].Trim());
}
}
}
return physicalIds.Count * GetCoresPerPhysicalCpu();
}
catch
{
return Environment.ProcessorCount / 2; // fallback
}
}
static int GetCoresPerPhysicalCpu()
{
try
{
var cpuInfo = System.IO.File.ReadAllText("/proc/cpuinfo");
var lines = cpuInfo.Split('\n');
foreach (var line in lines)
{
if (line.StartsWith("cpu cores"))
{
var parts = line.Split(':');
if (parts.Length > 1 && int.TryParse(parts[1].Trim(), out int cores))
{
return cores;
}
}
}
}
catch { }
return 1; // fallback
}
}
}