Certainly! Here's an example of C++ code using the Windows API to detect CPU bound threads:
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#include <vector>
// Function to check if a thread is CPU bound
bool IsThreadCPUBound(DWORD threadId)
{
HANDLE hThread = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, threadId);
if (hThread == NULL)
{
std::cerr << "Failed to open thread: " << threadId << std::endl;
return false;
}
FILETIME creationTime, exitTime, kernelTime, userTime;
if (!GetThreadTimes(hThread, &creationTime, &exitTime, &kernelTime, &userTime))
{
std::cerr << "Failed to get thread times for thread: " << threadId << std::endl;
CloseHandle(hThread);
return false;
}
ULONGLONG kernelTimeMs = (static_cast<ULONGLONG>(kernelTime.dwHighDateTime) << 32) | kernelTime.dwLowDateTime;
ULONGLONG userTimeMs = (static_cast<ULONGLONG>(userTime.dwHighDateTime) << 32) | userTime.dwLowDateTime;
CloseHandle(hThread);
// Threshold to determine if a thread is CPU bound
const ULONGLONG cpuBoundThresholdMs = 500; // Adjust this value based on your requirements
// Check if both kernel time and user time exceed the threshold
return kernelTimeMs > cpuBoundThresholdMs && userTimeMs > cpuBoundThresholdMs;
}
int main()
{
DWORD processId = GetCurrentProcessId();
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
if (hProcess == NULL)
{
std::cerr << "Failed to open process: " << processId << std::endl;
return 1;
}
// Get the process's thread list
DWORD threadIds[1024];
DWORD threadCount = GetProcessIdOfThread(hProcess);
if (!EnumThreadWindows(threadIds, sizeof(threadIds), &threadCount))
{
std::cerr << "Failed to enumerate threads for process: " << processId << std::endl;
CloseHandle(hProcess);
return 1;
}
std::vector<DWORD> cpuBoundThreads;
// Iterate through the threads and check if they are CPU bound
for (DWORD i = 0; i < threadCount; i++)
{
DWORD threadId = threadIds[i];
if (IsThreadCPUBound(threadId))
{
cpuBoundThreads.push_back(threadId);
}
}
CloseHandle(hProcess);
// Print the CPU bound threads
if (cpuBoundThreads.empty())
{
std::cout << "No CPU bound threads found." << std::endl;
}
else
{
std::cout << "CPU bound threads: ";
for (const DWORD threadId : cpuBoundThreads)
{
std::cout << threadId << " ";
}
std::cout << std::endl;
}
return 0;
}
Please note that this code uses the Windows API functions OpenThread, GetThreadTimes, OpenProcess, and EnumThreadWindows to retrieve the thread information and CPU times. Make sure to link against Kernel32.lib and Psapi.lib. Also, adjust the value as per your requirements to determine what threshold constitutes a CPU bound thread.