How to find the Number of physical CPU Cores (not logical SMT hyperthreads) via .NET Core?
Asked Answered
U

0

7

I want to detect the number of real physical cores, not logical cores, for workloads that scale negatively when more threads compete for private per-core caches, and/or have high enough IPC that running more than one logical thread per core doesn't increase throughput by more than the increase in threading overhead, especially for problems that don't scale perfectly to lots of cores.

Or to put it another way, the number of threads that can run without any of them competing for execution resources with each other, except memory bandwidth. (Editor's note: some alternatives to hyperthreading, like AMD Bulldozer-family CMP have 2 integer cores sharing an FPU/SIMD unit; you might want to count that as 2 real cores depending on the workload, even if you don't want to count 2 logical cores sharing a physical core with SMT such as Intel's Hyperthreading.)


I know similar questions has been asked before, but answers look outdated. Or Getting physical processor count .NET Core 2.2 is unanswered, with the code in the question not being fully portable.

System.Environment.ProcessorCount returns the count of logical cores only, so the double amount at my hyper threading system. For some intensive parallel calculation it is most efficient to start no more threads than physical cores available - at least my tests showed a significant performance loss when I started more threads.

I found some windows only solutions calling WMI or the kernel.dll to get the count of physical cores. But how to do at .net core to keep platform independence? Is there somewhere a hidden core count or a reliable way to calculate it?

The most promising idea I found up to now is to do some longer calculation at one thread and measure the time for it. Then do the same calculation at parallel (a.e. ProcessorCount threads) and measure the total time. Compare the two times to guess the count of physical cores. This may work, but looks costly and unreliable to me.

Undergarment answered 19/3, 2020 at 10:37 Comment(3)
Does this answer your question? Question about Environment.ProcessorCountOtorhinolaryngology
This property returns number of logical processors. If you have 4 physical cores and HT, it'll returns 8Otorhinolaryngology
Getting physical processor count .NET Core 2.2 is a duplicate but without an answer. Find number of cores on a linux machine using .Net Core failed with error (Unterminated quoted String) attempts a Linux-specific approach. This answer shows how .NET determines this internally. It might simply be that there is no platform-independent interface for retrieving this information because any method for doing so will naturally be platform-dependent.Dabber

© 2022 - 2024 — McMap. All rights reserved.