如何让 win32pdhutil 使用斜杠查询性能计数器?

How can I get win32pdhutil to query a performance counter with a slash?

我正在尝试使用 Python 中的 pywin32 包中的 win32pdhutil 查询 Windows 性能计数器,但我 运行 进入了一个每当计数器名称有斜线时出错。

例如,这段代码工作正常:

import win32pdhutil

query = win32pdhutil.GetPerformanceAttributes("Memory", "Available Bytes")

但是这段代码失败了:

import win32pdhutil

query = win32pdhutil.GetPerformanceAttributes("Memory", "Cache Faults/sec")

错误信息是:

Traceback (most recent call last):
  File "<path>\Python\Python38-32\lib\site-packages\win32\lib\win32pdhutil.py", line 61, in GetPerformanceAttributes
    type, val = win32pdh.GetFormattedCounterValue(hc, format)
pywintypes.error: (-1073738810, 'GetFormattedCounterValue', 'The data is not valid.')

我尝试了很多不同的计数器,但只有 运行 当计数器名称中有斜杠时才解决这个问题。

我的原始代码使用 win32pdh.AddCounter 和 win32pdh.CollectQueryData 具有相同的问题,但上面的示例在一行中演示了它。

我找到了一个类似的线程 here,但没有明显的解决方案。

您需要等待 "cache faults/sec" 收集到足够的数据,这是 msdn 上性能计数器的 c++ 示例 api:

Browsing Performance Counters

并且在 python 中,如果我在 win32pdhutil.py 中的 GetPerformanceAttributes 函数中硬编码(仅用于测试)如下:

def GetPerformanceAttributes(object, counter, instance = None, inum=-1,
                             format = win32pdh.PDH_FMT_LONG, machine=None):
    # NOTE: Many counters require 2 samples to give accurate results,
    # including "% Processor Time" (as by definition, at any instant, a
    # thread's CPU usage is either 0 or 100).  To read counters like this,
    # you should copy this function, but keep the counter open, and call
    # CollectQueryData() each time you need to know.
    # See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938
    # and http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
    # My older explanation for this was that the "AddCounter" process forced
    # the CPU to 100%, but the above makes more sense :)
    path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
    hq = win32pdh.OpenQuery()
    try:
        hc = win32pdh.AddCounter(hq, path)
        try:
            win32pdh.CollectQueryData(hq)
            time.sleep(1)
            win32pdh.CollectQueryData(hq)
            type, val = win32pdh.GetFormattedCounterValue(hc, format)
            return val
        finally:
            win32pdh.RemoveCounter(hc)
    finally:
        win32pdh.CloseQuery(hq)

然后"Cache Faults/sec"适合我,你可以尝试定制你自己的m_GetFormattedCounterValue功能,然后给收集器足够的时间来收集数据,就像上面的例子一样。