无法知道应用程序使用了多少个内核。但你可以通过它拥有的线程数来猜测它。
对于窗户:
您将需要使用微软所说的工具帮助库。更具体地说,您将需要查看遍历线程列表示例,该示例可以获取应用程序拥有的线程数。
微软真的很喜欢把他们的例子做得尽可能丑陋,所以这是我想出的一个美化版本,你给它一个 PID,它列出了与之相关的所有线程:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <cstdio>
bool list(unsigned int PID);
int main(void)
{
list(5532);
list(GetCurrentProcessId());
return 0;
}
bool list(unsigned int PID)
{
HANDLE thread_snap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32;
// Take a snapshot of all running threads
thread_snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (thread_snap == INVALID_HANDLE_VALUE) return false;
// Fill in the size of the structure before using it.
te32.dwSize = (DWORD)sizeof(THREADENTRY32);
// Retrieve information about the first thread, and exit if unsuccessful
if (!Thread32First(thread_snap, &te32))
{
CloseHandle(thread_snap);
return false;
}
// Now walk the thread list of the system, and display information about each thread associated with the specified process
printf("Printing threads for PID %u\n", PID);
do
{
if (te32.th32OwnerProcessID == PID)
{
printf( "THREAD ID = 0x%08X with base priority %u and delta priority %u\n", (unsigned int)te32.th32ThreadID, (unsigned int)te32.tpBasePri, (unsigned int)te32.tpDeltaPri);
}
}
while (Thread32Next(thread_snap, &te32));
printf("Done printing threads for PID %u\n\n", PID);
// Don't forget to clean up the snapshot object.
CloseHandle(thread_snap);
return true;
}
Run Code Online (Sandbox Code Playgroud)
输入:
5532(我的steam服务进程ID),GetCurrentProcessId()
输出:
Printing threads for PID 5532
THREAD ID = 0x00000BCC with base priority 8 and delta priority 0
THREAD ID = 0x0000041C with base priority 8 and delta priority 0
THREAD ID = 0x00001924 with base priority 8 and delta priority 0
THREAD ID = 0x00000C9C with base priority 8 and delta priority 0
Done printing threads for PID 5532
Printing threads for PID 9836
THREAD ID = 0x000000FC with base priority 8 and delta priority 0
Done printing threads for PID 9836
Run Code Online (Sandbox Code Playgroud)
您可以假设,如果应用程序使用的线程数多于 cpu 的核心数,则它可能会使用所有线程,如果应用程序使用的线程数较少,则可能会使用 x 个核心数,其中 x 是线程数。
如果您想更进一步,您可以获取每个线程的 CPU 使用情况,以便更好地估计它使用的内核数量。
我不完全确定是否可行的另一种方法是获取应用程序所有线程的 CPU 使用率并将它们相加(以百分比形式),获取系统拥有的核心数,将该数字提高到 - 1 并将其乘以 100 ( x^-1*100),其中 x 是核心数量,然后将所有线程的 CPU 使用率百分比除以核心可以处理的百分比,以估算出其使用的核心数量。
例如:
假设有 4 个内核和一个具有 4 个线程的应用程序,其中每个线程 2 个的 CPU 使用率为 25%,另外 2 个线程的 CPU 使用率每个为 11%。
您可以假设它使用:
(25+25+11+11)/((4^-1)*100) = 2.88 核
问题:
可能并非所有内核的时钟速度都相同。在这种情况下,它不会按预期工作。
如果您使用的是 c++11,您可以使用 来了解系统的核心数量std::thread::hardware_concurrency()。
或者,您也可以遍历进程列表并从那里获取进程拥有的线程数,但它没有像遍历线程那样拥有有关每个线程的高级信息。