将性能数据写入日志文件

Writing Performance Data to a Log File

本文关键字:日志 文件 性能 数据      更新时间:2023-10-16

我正在尝试使用其中一个Windows示例来获得一些CPU数据。当我尝试调试以下代码时,我收到消息"命令行必须包含有效的日志文件名"我正在使用MS Visual Studio 2013,并且我对总处理器时间感兴趣。

请指教。

有关代码的更多详细信息:http://msdn.microsoft.com/en-us/library/windows/desktop/aa373228(v=vs.85).aspx

守则:

#include <windows.h>
#include <stdio.h>
#include <pdh.h>
#include <pdhmsg.h>
#pragma comment(lib, "pdh.lib")
CONST PWSTR COUNTER_PATH = L"\Processor(0)\% Processor Time";
CONST ULONG SAMPLE_INTERVAL_MS = 1000;
void DisplayCommandLineHelp(void)
{
    wprintf(L"The command line must include a valid log file name.n");
}
void wmain(int argc, WCHAR **argv)
{
    HQUERY hQuery = NULL;
    HLOG hLog = NULL;
    PDH_STATUS pdhStatus;
    DWORD dwLogType = PDH_LOG_TYPE_CSV;
    HCOUNTER hCounter;
    DWORD dwCount;
    if (argc != 2)
    {
        DisplayCommandLineHelp();
        goto cleanup;
    }
    // Open a query object.
    pdhStatus = PdhOpenQuery(NULL, 0, &hQuery);
    if (pdhStatus != ERROR_SUCCESS)
    {
        wprintf(L"PdhOpenQuery failed with 0x%xn", pdhStatus);
        goto cleanup;
    }
    // Add one counter that will provide the data.
    pdhStatus = PdhAddCounter(hQuery,
        COUNTER_PATH,
        0,
        &hCounter);
    if (pdhStatus != ERROR_SUCCESS)
    {
        wprintf(L"PdhAddCounter failed with 0x%xn", pdhStatus);
        goto cleanup;
    }
    // Open the log file for write access.
    pdhStatus = PdhOpenLog(argv[1],
        PDH_LOG_WRITE_ACCESS | PDH_LOG_CREATE_ALWAYS,
        &dwLogType,
        hQuery,
        0,
        NULL,
        &hLog);
    if (pdhStatus != ERROR_SUCCESS)
    {
        wprintf(L"PdhOpenLog failed with 0x%xn", pdhStatus);
        goto cleanup;
    }
    // Write 10 records to the log file.
    for (dwCount = 0; dwCount < 10; dwCount++)
    {
        wprintf(L"Writing record %dn", dwCount);
        pdhStatus = PdhUpdateLog(hLog, NULL);
        if (ERROR_SUCCESS != pdhStatus)
        {
            wprintf(L"PdhUpdateLog failed with 0x%xn", pdhStatus);
            goto cleanup;
        }
        // Wait one second between samples for a counter update.
        Sleep(SAMPLE_INTERVAL_MS);
    }
cleanup:
    // Close the log file.
    if (hLog)
        PdhCloseLog(hLog, 0);
    // Close the query object.
    if (hQuery)
        PdhCloseQuery(hQuery);
}
if (argc != 2)
{
    DisplayCommandLineHelp();
    goto cleanup;
}

这是你的答案。您需要将项目设置为在程序运行时将文件名传递给程序。

argc计算程序收到的命令行参数数。它总是至少得到一个,程序本身的名称。但是这个程序需要第二个,即要写入的日志文件的名称。