本帖最后由 gordian693 于 2012-01-19 15:42:37 编辑

解决方案 »

  1.   

    用API测进程在双核PC的CPU使用率我先用WINXP自带的perfmon测一个进程的CPU使用率,这个进程的使用率有时会超过100%,因为是在双核电脑中,计数器% Processor Time是以单核的为标准。 
    然后我用PdhGetFormattedCounterValue还是测这个进程的CPU使用率,还是用的计数器% Processor Time,问题来了,在perfmon中显示CPU使用率超过100%的时间,我用PdhGetFormattedCounterValue测出的值却只是100%,怎么解决这个问题?不知道我把意思说清楚没有。下面是代码。 #include "stdafx.h" 
    #include <Pdh.h> 
    #include <stdlib.h> 
    #include <conio.h> 
    #include <windows.h> 
    #include <iostream> 
    #include <iomanip> 
    using namespace std; const int SampleTime = 1000;  
    PDH_STATUS     status; 
    PDH_HQUERY     hQuery; 
    HCOUNTER       *pCounterHandle; 
    wchar_t        szPathBuffer = L"\\Processor(1)\\% Processor Time"; 
    SYSTEMTIME     szSampleTime; 
    DWORD          ctrType; 
    PDH_FMT_COUNTERVALUE Value; int _tmain(int argc, _TCHAR* argv) 

    int duration = 0; 
    double LastValue = 0.0; 
    double sum = 0.0, average = 0.0, max = 0.0; 
    status = PdhOpenQuery(0, 0, &hQuery); 
    if(status != ERROR_SUCCESS) 
    exit(1); 
    pCounterHandle = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER)); 
        status = PdhAddCounter(hQuery, szPathBuffer, 0, pCounterHandle); 
        while (!_kbhit()) 

    GetLocalTime(&szSampleTime); 
    status = PdhCollectQueryData(hQuery); 
    cout << setw(2) << setfill('0') << szSampleTime.wHour    << ": " 
     << setw(2) << setfill('0') << szSampleTime.wMinute  << ": " 
     << setw(2) << setfill('0') << szSampleTime.wSecond  << "    "; 
        status = PdhGetFormattedCounterValue (*pCounterHandle, PDH_FMT_DOUBLE, &ctrType, &Value); 
    if(LastValue > 0 && Value.doubleValue == 0) 

    printf("CPU Usage: %-7.3f  Time: %d", Value.doubleValue, duration); 
    break; 

    printf("CPU Usage: %7.3f  ", Value.doubleValue); 
    Sleep(SampleTime); 
    if(Value.doubleValue > 0) 

    duration++; 
    if(max < Value.doubleValue) 
    max = Value.doubleValue; 
    sum = sum + Value.doubleValue; 
    average = sum / duration; 
    cout << "Time: " << duration; 

    cout << endl; 
    LastValue = Value.doubleValue; 

    cout << endl << "Over:" << endl; 
    cout << "Duration: " << duration << "  " << endl; 
    cout << "Average: " << average << "  Max: " << max << endl; 
    status = PdhCloseQuery(hQuery); 
    return 0; 

    这段代码是想测一个进程在一段时间内的平均CPU使用率,所以当实际的CPU使用率超过100%,而代码中得到的值仅为100%时会导致最后结果的不准确。 
      

  2.   

     性能计数器:   private PerformanceCounter cpuPerformance = new PerformanceCounter();   cpuPerformance.CategoryName = "Processor";
                cpuPerformance.CounterName = "% Processor Time";
                cpuPerformance.InstanceName = "_Total";  double y = cpuPerformance.NextValue();  //CPU的使用率
      

  3.   

    这个不知道了  估计windows的dll里有这个功能